Bob*_*ity 1 android kotlin android-livedata
我得到了实时数据观察者和一个需要来自两个观察者的结果的函数。当两个观察者都收到数据时如何调用这个函数?不是代码看起来像这样
firstViewModel.dataOne.observe(viewLifecycleOwner) {
secondViewModel.dataTwo.observe(viewLifecycleOwner) { dataTwoResult ->
setAssociateInfo(dataTwoResult, it) // <--- send two parameters from to observers together
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西应该可以工作(所有代码未经测试,但应该可以正常工作):
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 { })
Run Code Online (Sandbox Code Playgroud)
这将类似于结合最新的。
作为一个简单的扩展函数:
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) }
}
Run Code Online (Sandbox Code Playgroud)
用法 :
firstViewModel.dataOne.combineWith(secondViewModel.dataTwo)
.observe(viewLifecycowner, Observer { latestPairResult -> }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3340 次 |
| 最近记录: |