【发布时间】: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<User> 变量user 原样:
val user = userRepository.getUser(userId).asLiveData()
【问题讨论】:
-
可能是返回类型
Flow发挥了作用(我猜)。
标签: android kotlin kotlin-coroutines android-livedata kotlin-flow