-
Notifications
You must be signed in to change notification settings - Fork 36
1. ViewModel
Roxie uses Google Architecture Components ViewModel and LiveData
to hold immutable State. The ViewModel is conceptually a Store in Redux terms. It is the glue that links UI events with calls to the Domain layer.
The Reducer is managed by the ViewModel and is the only component that manages State. The State is never mutated--instead, the UI events produce a new State. This makes the ViewModel (our State container) a single source of truth. Since by design ViewModel survives orientation changes, we get the latest State emitted to the LifecycleObserver
after rotation or after our LifecycleOwner
re-enters foreground.
The ViewModels (State) can be observed by both Activities and Fragments. Given the recent single Activity with multiple Fragments recommendation from Google, the sample bundled with Roxie contains ViewModels with Fragments as their LifecycleOwner
s.
Here is an example of ViewModel responsible for managing a note listing screen:
class NoteListViewModel(
initialState: State?,
private val loadNoteListUseCase: GetNoteListUseCase
) : BaseViewModel<Action, State>() {
override val initialState = initialState ?: State(isIdle = true)
private val reducer: Reducer<State, Change> = { state, change ->
when (change) {
/* define the Reducer logic here */
}
}
init {
bindActions()
}
private fun bindActions() {
/* convert Actions into States here */
}
}
Check out the BaseViewModel
provided by Roxie for the common ViewModel functionality such as wrapping State in LiveData
, dispatching Actions, etc.