我正在考虑 Kotlin 协程和 LiveData。我想做真正的基本用例,其中 ViewModel 返回从 Repository 挂起函数中获取的 LiveData,该函数也返回 LiveData。
存储库函数签名:
suspend fun getAll() : LiveData<List<Mountain>>
它不能简单地做到这一点:
fun getMountains() : LiveData<List<Mountain>> {
return mountainsRepository.getAll()
}
因为编译器声明挂起函数应该从协程或另一个挂起函数调用。
我想出了两个丑陋的解决方案,但我知道它们并不优雅:
1 个使用 runBlocking 的解决方案
fun getMountains() : LiveData<List<Mountain>> = runBlocking { mountainsRepository.getAll() }
2 带有可为空 LiveData 的解决方案
fun getMountains() : LiveData<List<Mountain>>?{
var mountains : LiveData<List<Mountain>>? = null
viewModelScope.launch{
mountains = mountainsRepository.getAll()
}
return mountains
}
我怎样才能正确地做到这一点?
最佳答案
有一个liveData builder可以在其主体中调用挂起函数。
所以你的 View 模型函数看起来像
fun getMountains() = liveData {
emit(mountainsRepository.getAll())
}
确保您至少使用
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
正如莉娜所说 - 删除
suspend
来自您的存储库 getAll()
函数不要让它阻塞。拥有
fun getAll() : LiveData<List<Mountain>>
在你的 repo 中,和
fun getMountains() = mountainsRepository.getAll()
在您的 View 模型中,可能是实现相同目标的更好方法
关于kotlin - 在从暂停的存储库中获取的 ViewModel 中传递 LiveData 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351067/