android - 如何观察两个 LiveData 并一起使用结果。如何实现 MediatorLiveData?
问题描述
我得到了实时数据观察者和一个需要两个观察者结果的功能。当两个观察者都收到数据时如何调用这个函数?不是代码看起来像这样
firstViewModel.dataOne.observe(viewLifecycleOwner) {
secondViewModel.dataTwo.observe(viewLifecycleOwner) { dataTwoResult ->
setAssociateInfo(dataTwoResult, it) // <--- send two parameters from to observers together
}
}
解决方案
像这样的东西应该可以工作(所有代码都未经测试,但应该可以正常工作):
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 -> }
推荐阅读
- python - MSE,在 Tensorflow Keras 中使用未缩放数据进行评估是否正确?
- excel - 如果多行相等但一行不同
- r - 更新后将数据框从 Rstudio Viewer 复制粘贴到 Excel 无法正常工作
- stripe-payments - 如何在我的 asp.net 网络表单中使用 stripe.redirectToCheckout?
- r - 使用培根分解时必须提供来源
- c - 如何在 C 中包含头文件
- html - 按钮被点击后正在移动
- python - 使用python在同一图中绘制来自不同数据文件的多行
- matlab - 键入变量的第一个字母以快速到达 Matlab 工作区中的那个位置
- firebase - Firebase 云存储:“UploadTask”未定义类