Step #5: Updating SingleModelMotor
We need to make similar adjustments to SingleModelMotor
that we made to RosterMotor
.
With that in mind, add this view-state class above the declaration of SingleModelMotor
:
data class SingleModelViewState(
val item: ToDoModel? = null
)
And, replace the current SingleModelMotor
implementation with:
class SingleModelMotor(
private val repo: ToDoRepository,
modelId: String?
) : ViewModel() {
val states = repo.find(modelId)
.map { SingleModelViewState(it) }
.stateIn(viewModelScope, SharingStarted.Eagerly, SingleModelViewState())
fun save(model: ToDoModel) {
viewModelScope.launch {
repo.save(model)
}
}
fun delete(model: ToDoModel) {
viewModelScope.launch {
repo.delete(model)
}
}
}
SingleModelViewState
is akin to RosterViewState
, wrapping a single model object… or null
, since we may not have a model (e.g., for a new to-do item).
states
works like the RosterMotor
edition, except that it calls find()
on the ToDoRepository
rather than all()
. But, like RosterMotor
, it maps the result to a view-state and it converts the Flow
into a StateFlow
.
save()
and delete()
both wrap their corresponding ToDoRepository
calls in viewModelScope.launch()
, so that those coroutines get run in our desired CoroutineScope
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.