Last active
June 7, 2022 21:27
-
-
Save rwbutler/9e199a43c46fe437ba3f302871d0713c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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