Last active
July 17, 2021 16:49
-
-
Save abhimuktheeswarar/5e358e98d6958fdca81d04eb9d8ec2e5 to your computer and use it in GitHub Desktop.
Simple CounterViewModel
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
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