Skip to content

Instantly share code, notes, and snippets.

@rwbutler
Last active June 8, 2022 06:57
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/c5f771943a423a6b288a831baf4cba9e to your computer and use it in GitHub Desktop.
Save rwbutler/c5f771943a423a6b288a831baf4cba9e to your computer and use it in GitHub Desktop.
protocol ViewModel {
func viewDidAppear()
func viewDidDisappear()
}
class SimpleViewModel: ViewModel {
private var cancellables = Set<AnyCancellable>()
private var previousBrightness: Double?
private let screenBrightnessService: ScreenBrightnessService
init(screenBrightnessService: ScreenBrightnessService) {
self.screenBrightnessService = screenBrightnessService
subscribe(to: screenBrightnessService.publisher)
}
private func subscribe(to screenBrightness: ScreenBrightnessPublisher) {
screenBrightness.filter { brightness in
brightness != 1.0 // We're not interested in cases where brightness has been set to maximum.
}
.map { brightness -> Double? in
brightness // Map to an optional so we can assign to the optional instance variable.
}
.assign(to: \.previousBrightness, on: self)
.store(in: &cancellables)
}
func viewDidAppear() {
screenBrightnessService.set(to: 1.0) // 1 is full brightness (values range 0 - 1).
}
func viewDidDisappear() {
guard let previousBrightness = previousBrightness else {
return
}
screenBrightnessService.set(to: previousBrightness)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment