【问题标题】:Confused about official Android documentation on Flow对 Flow 上的官方 Android 文档感到困惑
【发布时间】:2022-04-16 18:26:12
【问题描述】:

我参考了recommended app architecture中关于使用Flow库的Android官方文档。

在UserRepository 类中:

class UserRepository @Inject constructor(...) {
   fun getUser(userId: String): Flow<User> {
       refreshUser(userId)
       // Returns a Flow object directly from the database.
       return userDao.load(userId)
   }

   private suspend fun refreshUser(userId: String) {
       ...
   }

   ...
}

不明白refreshUser()这个挂起函数怎么能在getUser()这个非挂起函数中调用。也许我错过了什么。

我正在尝试创建与此类非常相似的东西,并且正如预期的那样,我收到一个编译错误,指出只能在另一个挂起函数中调用挂起函数。完成这项工作所需的最小更改是什么,以便在UserProfileViewModel 中,我可以保持LiveData&lt;User&gt; 变量user 原样:

val user = userRepository.getUser(userId).asLiveData()

【问题讨论】:

  • 可能是返回类型Flow 发挥了作用(我猜)。

标签: android kotlin kotlin-coroutines android-livedata kotlin-flow


【解决方案1】:

你不能在non-suspend函数中调用suspend函数,所以函数getUser()有一个错误Suspend function 'refreshUser' should be called only from a coroutine or another suspend function。要使此错误消失,请添加 suspend 关键字:

suspend fun getUser(userId: String): Flow<User> { ... }

要使您的第二个代码正常工作,您需要使用liveData builder。

val user = liveData<User> { 
    emitSource(getUser(userId).asLiveData())
}

在liveData builder 中,您可以调用suspend 函数,尤其是getUser(userId)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多