首页 > 解决方案 > 如何观察两个 LiveData 并一起使用结果。如何实现 MediatorLiveData?

问题描述

我得到了实时数据观察者和一个需要两个观察者结果的功能。当两个观察者都收到数据时如何调用这个函数?不是代码看起来像这样

firstViewModel.dataOne.observe(viewLifecycleOwner) {
        secondViewModel.dataTwo.observe(viewLifecycleOwner) { dataTwoResult ->
            setAssociateInfo(dataTwoResult, it) // <--- send two parameters from to observers together
        }
    }

标签: androidkotlinandroid-livedata

解决方案


像这样的东西应该可以工作(所有代码都未经测试,但应该可以正常工作):

val a : MutableLiveData<Int> = MutableLiveData(1)
val b : MutableLiveData<String> = MutableLiveData("B")

val c : MediatorLiveData<Pair<Int?, String?>> = MediatorLiveData<Pair<Int?, String?>>().apply {
    addSource(a) { value = Pair(it, b.value) }
    addSource(b) { value = Pair(a.value, it) }
}

c.observe(lco, Observer {  })

这将类似于结合最新的。

作为一个简单的扩展功能:

fun <T, S> LiveData<T?>.combineWith(other: LiveData<S?>): LiveData<Pair<T?, S?>> =
    MediatorLiveData<Pair<T?, S?>>().apply {
        addSource(this@combineWith) { value = Pair(it, other.value) }
        addSource(other) { value = Pair(this@combineWith.value, it) }
    }

用法 :

firstViewModel.dataOne.combineWith(secondViewModel.dataTwo)
              .observe(viewLifecycowner, Observer { latestPairResult ->  }

推荐阅读