Skip to content

Instantly share code, notes, and snippets.

@rwbutler
Last active June 7, 2022 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwbutler/9e199a43c46fe437ba3f302871d0713c to your computer and use it in GitHub Desktop.
Save rwbutler/9e199a43c46fe437ba3f302871d0713c to your computer and use it in GitHub Desktop.
protocol ScreenBrightnessService3 {
var publisher: ScreenBrightnessPublisher { get }
func set(to value: Double)
}
class UIKitScreenBrightnessService3: ScreenBrightnessService3 {
private let brightnessSubject: CurrentValueSubject<Double, Never>
private var cancellables = Set<AnyCancellable>()
var publisher: ScreenBrightnessPublisher { // i.e. AnyPublisher<Double, Never>
brightnessSubject.eraseToAnyPublisher()
}
private let screenBrightness: ScreenBrightness
init(notificationPublisher: AnyPublisher<Notification, Never>, screenBrightness: ScreenBrightness) {
brightnessSubject = CurrentValueSubject<Double, Never>(screenBrightness.brightness)
self.screenBrightness = screenBrightness
subscribe(to: notificationPublisher)
}
func set(to value: Double) {
screenBrightness.brightness = value
}
private func subscribe(to notificationPublisher: AnyPublisher<Notification, Never>) {
notificationPublisher
.compactMap { [weak self] _ -> Double? in
guard let self = self else {
return nil
}
return self.screenBrightness.brightness // Swift 5.5 automatically converts between CGFloat and Double.
}
.assign(to: \.brightnessSubject.value, on: self)
.store(in: &cancellables)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment