Skip to content

Instantly share code, notes, and snippets.

@linean
Created April 13, 2022 17:14
Show Gist options
  • Save linean/04fa039019984410535d2f7e97a523bd to your computer and use it in GitHub Desktop.
Save linean/04fa039019984410535d2f7e97a523bd to your computer and use it in GitHub Desktop.
class ViewModel {
private val events = Channel<Event>()
val state = MutableStateFlow(State())
init {
events.receiveAsFlow()
.onEach(::updateState)
.launchIn(viewModelScope)
}
fun handleEvent(event: Event) {
events.trySend(event)
}
private fun updateState(event: Event) {
when (event) {
is Increment -> state.update { it.copy(counter = it.counter + 1) }
is Decrement -> state.update { it.copy(counter = it.counter - 1) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment