我正在将此代码示例迁移到 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
}
...
}
此示例取自https://commonsware.com/AndExplore/ book
我可以想到这个解决方案,但我不确定这是否是最好的方法
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
}
}
}
那么我们如何使用 StateFlow 来实现这个场景。