android - 谷歌应用架构指南暂停功能错误
问题描述
我正在使用谷歌指南为我的新 android 应用程序构建架构( https://developer.android.com/jetpack/guide )。但是,当我如上所述使用 Flow 从房间数据库返回数据时,出现了一些意外:
@HiltViewModel
class CategoriesViewModel @Inject constructor(categoriesRepository:CategoriesRepository) : ViewModel() {
var categories : LiveData<List<Category>> =
categoriesRepository.getCategories().asLiveData()
}
class CategoriesRepository @Inject constructor(val categoryDao: CategoryDao) {
suspend fun getCategories(): Flow<List<Category>> {
refreshCategories()
// Returns a Flow object directly from the database.
return categoryDao.getAll()
}
private suspend fun refreshCategories() {
val response = ApiInterface.create().getCategories()
categoryDao.insertAll(response.data!!)
}
}
错误是:暂停函数“getCategories”只能从协程或另一个暂停函数中调用。但在指南中,这些功能是挂起功能。如何修复此错误?
解决方案
您正在getCategories()
从非暂停CategoriesViewModel
构造函数调用暂停。
在您链接的指南中,构造函数代码将挂起函数调用包装在
viewModelScope.launch {
...
}
推荐阅读
- r - 在 R 中保存指定环境的语法是什么?
- tensorflow - 神经网络回归的 NaN 泊松损失值
- swift - NSFont.TextStyleOptionKey 中可以使用哪些值
- python - 如何防止版主在 discord.py 中互相使用版主命令?
- azure - 证书 VerifyNoRevocation() 在 Azure APIM 中返回 false - 幕后发生了什么?
- laravel - Laravel 8 - 没有数据库连接的资源路由
- pydantic - 如何使用 pydantic 创建 MappingModel?
- flutter - FlutterError (setState() 在 dispose() 之后调用:_StartPageState#13a2d(生命周期状态:已失效,未安装)
- ios - 503 响应仅在特定设备上一次通话(iOS 应用程序)
- javascript - 自引用 JSON 数组以调用函数/进行更新