我正在尝试将数据从服务器和缓存到数据库中,并将新的获取列表返回给用户。我正在获取响应表单服务器并将其保存到本地数据库,但是当我尝试从可组合函数中观察它时,它显示列表为空。
当我尝试在myViewModel类中调试和收集流数据时,它显示但不显示是可组合函数。
道
@Dao
interface CategoryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(categories: List<Category>)
@Query("SELECT * FROM categories ORDER BY name")
fun read(): Flow<List<Category>>
@Query("DELETE FROM categories")
suspend fun clearAll()
}
存储库类:
suspend fun getCategories(): Flow<List<Category>> {
val categories = RetrofitModule.getCategories().categories
dao.insert(categories)
return dao.read()
}
我的视图模型
fun categoriesList(): Flow<List<Category>> {
var list: Flow<List<Category>> = MutableStateFlow(emptyList())
viewModelScope.launch {
list = repository.getCategories().flowOn(Dispatchers.IO)
}
return list
}
观察来自:
@Composable
fun StoreScreen(navController: NavController, viewModel: CategoryViewModel) {
val list = viewModel.categoriesList().collectAsState(emptyList())
Log.d("appDebug", list.value.toString()) // Showing always emptyList []
}
当前响应 :
2021-05-15 16:08:56.017 5125-5125/com.demo.app D/appDebug: []
您永远不会更新MutableStateFlow
的value
,该已在Composable
函数中收集为状态。
此外,还将Flow
类型对象分配给MutableStateFlow
变量。
我们可以使用以下方法更新撰写中collected
流的值:-
mutableFlow.value = newValue
我们需要将列表类型更改为MutableStateFlow<List<Category>>
而不是Flow<List<Category>>
试试这个:-
var list: MutableStateFlow<List<Category>> = MutableStateFlow(emptyList()) // changed the type of list to mutableStateFlow
viewModelScope.launch {
repository.getCategories().flowOn(Dispatchers.IO).collect { it ->
list.value = it
}
}