首页 > 解决方案 > 谷歌应用架构指南暂停功能错误

问题描述

我正在使用谷歌指南为我的新 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”只能从协程或另一个暂停函数中调用。但在指南中,这些功能是挂起功能。如何修复此错误?

标签: androidkotlinkotlin-coroutines

解决方案


您正在getCategories()从非暂停CategoriesViewModel构造函数调用暂停。

在您链接的指南中,构造函数代码将挂起函数调用包装在

viewModelScope.launch {
    ...
}

推荐阅读