Last active
June 8, 2022 06:57
-
-
Save rwbutler/c5f771943a423a6b288a831baf4cba9e 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 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