kotlin - 在从暂停的存储库中获取的 ViewModel 中传递 LiveData 的正确方法

标签 kotlin android-livedata kotlin-coroutines android-viewmodel

我正在考虑 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/

相关文章:

android - 实时数据库显示数据是否仍未上传

java - 如何在 Kotlin 中实现模板方法设计模式?

kotlin - kotlin-react useEffect中如何订阅StateFlow

android - 线程 "Test worker"java.lang.IllegalStateException : Module with the Main dispatcher had failed to initialize 中的异常

android - 如何结合 livedata 和 kotlin flow

android - Unresolved reference : Libraries - buildSrc

kotlin - 如何用http4k在中间建模一个路径参数

android - 如何在另一个 ViewModel 中使用来自一个 ViewModel 的数据

Android LiveData Observer 在性能方面的替代方案

android - MVVM:复杂 View / View 模型-> 多个 LiveData 对象?