I am migrating this code sample to StateFlow.
class RosterMotor(private val repo: ToDoRepository) : ViewModel() {
private val _states = MediatorLiveData<RosterViewState>()
val states: LiveData<RosterViewState> = _states
private var lastSource: LiveData<RosterViewState>? = null
init {
load(FilterMode.ALL)
}
fun load(filterMode: FilterMode) {
lastSource?.let { _states.removeSource(it) }
val items =
repo.items(filterMode).map { RosterViewState(it, filterMode) }.asLiveData()
_states.addSource(items) { viewstate ->
_states.value = viewstate
}
lastSource = items
}
...
}
This sample is taken from https://commonsware.com/AndExplore/ book
I can think of this solution but I am not sure if this is the best way
private val _states = MutableStateFlow(RosterViewState())
val states: StateFlow<RosterViewState> = _states
init {
load(ALL)
}
fun load(filterMode: FilterMode) {
viewModelScope.launch {
repository.items(filterMode).map { RosterViewState(it, filterMode) }
.collect {
_states.value = it
}
}
}
So how we can implement this scenario using StateFlow.