-
Notifications
You must be signed in to change notification settings - Fork 6
Android
Miguel Panelo edited this page Feb 10, 2019
·
1 revision
The natural thing to do is to put Kaskade in a ViewModel.
class ToDoViewModel : ViewModel() {
// Create the Kaskade
private val kaskade = Kaskade.create<TodoAction, TodoState>(TodoState.OnLoaded(listOf())) {
on<TodoAction.Refresh> {
TodoState.OnLoaded(todoRepository.getToDoItems())
}
on<TodoAction.Delete> {
todoRepository.removeItem(action.todoItem)
TodoState.OnDeleted(action.position)
}
on<TodoAction.Add> {
todoRepository.addItem(action.todoItem)
TodoState.OnAdded(action.todoItem)
}
on<TodoAction.Update> {
todoRepository.updateItem(action.todoItem)
TodoState.OnUpdated(action.position, action.todoItem)
}
}
// Expose the state by using the LiveData extension
val state = kaskade.stateLiveData()
// Abstract the call to `kaskade.process()`
fun process(action: TodoAction) {
kaskade.process(action)
}
// You can do unsubscription calls in the `onClear` method
override fun onCleared() {
super.onCleared()
kaskade.unsubscribe()
}
}
Handling process death can be done by just declaring kaskade as a lateinit var
and create the kaskade when you already have the initial state from resuming the application.
class ToDoViewModel : ViewModel() {
private lateinit var kaskade: Kaskade<TodoAction, TodoState>
fun restore(state: TodoState = TodoState.OnLoaded(listOf())) {
if (::kaskade.isInitialized.not()) {
kaskade = createKaskade(state)
}
}
// Create the Kaskade
fun createKaskade(state: TodoState) = Kaskade.create<TodoAction, TodoState>(state) {
on<TodoAction.Refresh> {
TodoState.OnLoaded(todoRepository.getToDoItems())
}
on<TodoAction.Delete> {
todoRepository.removeItem(action.todoItem)
TodoState.OnDeleted(action.position)
}
on<TodoAction.Add> {
todoRepository.addItem(action.todoItem)
TodoState.OnAdded(action.todoItem)
}
on<TodoAction.Update> {
todoRepository.updateItem(action.todoItem)
TodoState.OnUpdated(action.position, action.todoItem)
}
}
. . .
}
You can also put the initial state in the parameter of the ViewModel but for cases with dependency injection frameworks is being used, it might add more complexity to the application.