Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Last active July 17, 2021 16:49
Show Gist options
  • Save abhimuktheeswarar/5e358e98d6958fdca81d04eb9d8ec2e5 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/5e358e98d6958fdca81d04eb9d8ec2e5 to your computer and use it in GitHub Desktop.
Simple CounterViewModel
class CounterViewModel(private val store: Store<CounterState>) : ViewModel() {
val actions: Flow<Action> = store.actions
val states: Flow<CounterState> = store.states
override fun onCleared() {
super.onCleared()
store.terminate()
}
companion object {
private val reduce = { action: Action, state: CounterState ->
when (action) {
is CounterAction.IncrementAction -> {
state.copy(counter = state.counter + 1)
}
is CounterAction.DecrementAction -> {
state.copy(counter = state.counter - 1)
}
is CounterAction.ForceUpdateAction -> {
state.copy(counter = action.count)
}
is CounterAction.ResetAction -> {
state.copy(counter = 0)
}
else -> state
}
}
fun get(): CounterViewModel {
val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
val store = Store(
initialState = CounterState(),
reduce = reduce,
scope = scope
)
return CounterViewModel(store)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment