Last active
March 6, 2022 02:45
-
-
Save evilthreads669966/e9420addfd02e3856fe29c366d40d698 to your computer and use it in GitHub Desktop.
observer
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
fun main(){ | |
State.apply { | |
addObserver(StateView) | |
value = UiState.Created | |
value = UiState.Started | |
value = UiState.Resumed | |
value = UiState.Paused | |
value = UiState.Stopped | |
value = UiState.Destroyed | |
} | |
} | |
sealed class UiState(){ | |
object Initialized: UiState() | |
object Created: UiState() | |
object Started: UiState() | |
object Resumed: UiState() | |
object Paused: UiState() | |
object Stopped: UiState() | |
object Destroyed: UiState() | |
} | |
object State: Observable<UiState>{ | |
override val observers = mutableSetOf<Observer<UiState>>() | |
override var value: UiState = UiState.Initialized | |
set(value) { | |
if(value == this.value) return | |
field = value | |
this.update(field) | |
} | |
} | |
object StateView: Observer<UiState>{ | |
override fun update(value: UiState) { | |
when(value){ | |
UiState.Initialized -> println("The process has been created and the app is being opened.") | |
UiState.Created -> println("Creating the app UI") | |
UiState.Started -> println("Finished creating the UI. This is where data stored in stopped state is restored") | |
UiState.Resumed -> println("The UI is in interactive mode. This also where the user restores any data stored during the paused state.") | |
UiState.Paused -> println("The user requested to minimize the app. Storing data for rebuilding UI") | |
UiState.Stopped -> println("The app has been fully minimized and the user could be using another app. Storing data.") | |
UiState.Destroyed -> println("The app has been closed and the process has been killed.") | |
} | |
} | |
} | |
fun interface Observer<in T>{ | |
fun update(value: T) | |
} | |
interface Observable<T>{ | |
var value: T | |
val observers: MutableCollection<Observer<T>> | |
fun addObserver(vararg observer: Observer<T>) = this.observers.addAll(observer) | |
fun removeObserver(vararg observer: Observer<T>) = this.observers.removeAll(observer) | |
fun update(value: T) = observers.forEach { observer -> observer.update(value) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment