我试图在填充我的 ListAdapter 时从 LiveData 切换到 StateFlow。
我目前有一个MutableLiveData<List<CustomClass>>
我正在观察更新列表适配器的:
viewModel.mutableLiveDataList.observe(viewLifecycleOwner, Observer {
networkIngredientAdapter.submitList(it)
}
这工作正常。现在我将viewModel 中的 替换为MutableLiveData<List<CustomClass>?>
:MutableStateFlow<List<CustomClass>?>
private val _networkResultStateFlow = MutableStateFlow<List<IngredientDataClass>?>(null)
val networkResultStateFlow : StateFlow<List<IngredientDataClass>?>
get() = _networkResultStateFlow
fun loadCustomClassListByNetwork() {
viewModelScope.launch {
//a network request using Retrofit
val result = myApi.myService.getItems()
_networkResultStateFlow.value = result
}
}
我正在这样的片段中收集新列表:
lifecycleScope.launchWhenStarted {
viewModel.networkResultStateFlow.collect(){
list -> networkIngredientAdapter.submitList(list)}
}
但是,当我调用 loadCustomClassListByNetwork() 时,列表适配器不会更新。为什么我无法收集价值