【发布时间】:2021-08-09 12:06:33
【问题描述】:
我正在使用谷歌指南为我的新 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”只能从协程或其他暂停函数中调用。 但在指南中,这些功能是挂起功能。 如何解决此错误?
【问题讨论】:
标签: android kotlin kotlin-coroutines