【问题标题】:Google Guide to app architecture suspend function errorGoogle 应用架构指南暂停功能错误
【发布时间】: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


    【解决方案1】:

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

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

    viewModelScope.launch {
        ...
    }
    

    【讨论】:

    • 当我在viewmodel的init方法中使用viewModelScope时,片段中的viewModel.categories.observe返回nullPointer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2017-01-08
    • 2011-01-02
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多