一对多依赖 —— MediatorLiveData MediatorLiveData 允许您将一个或多个数据源添加到单个 LiveData 可观察对象。
示例:观察两个LiveData同时为 true 时, 执行相应的操作:
postLiveDataExample(liveData1, liveData2).observe(this, Observer {
if (it){
// TODO
}
})
fun postLiveDataExample(
liveData1: LiveData<Boolean>,
liveData2: LiveData<Boolean>
): LiveData<Boolean> {
val result = MediatorLiveData<Boolean>()
result.addSource(liveData1) { value ->
result.value = combineLatestData(liveData1, liveData2)
}
result.addSource(liveData2) { value ->
result.value = combineLatestData(liveData1, liveData2)
}
return result
}
private fun combineLatestData(
liveData1: LiveData<Boolean>,
liveData2: LiveData<Boolean>
): Boolean {
val value1 = liveData1.value
val value2 = liveData2.value
// Don't send a success until we have both results that are true
// if (value1 && value2) {
// return true
// }else{
// return false
// }
return value1 && value2
}
上面的 MediatorLiveData 示例显示了一些代码重复,因此我们可以利用 Kotlin 的扩展功能: 扩展写法:
/**
* 将值设置为一个函数的结果,该函数在两个 LiveData 都有数据或之后接收到更新时调用
*/
fun <T, A, B> LiveData<A>.combineAndCompute(
other: LiveData<B>,
onChange: (A?, B?) -> T
): MediatorLiveData<T> {
var source1emitted = false
var source2emitted = false
val result = MediatorLiveData<T>()
val mergeF = {
if (source1emitted && source2emitted) {
result.value = onChange.invoke(this.value, other.value)
}
}
result.addSource(this) { source1emitted = true; mergeF.invoke() }
result.addSource(other) { source2emitted = true; mergeF.invoke() }
return result
}
调用示例:
liveData1.combineAndCompute(liveData2){
value1, value2 -> value1 == true && value2 == true
}.observe(this){
if (it){
// TODO
}
}
|