美文网首页
合并多个liveData

合并多个liveData

作者: crossroads | 来源:发表于2019-12-12 17:10 被阅读0次

问: 如果一个按钮状态被两个liveData控制怎么办?只要有一个变了,按钮状态就要改变,
答:可以用MediatorLiveData。
例:来个封装例子~这里是四个源

class CombineLatestMediatorLiveDataOfFour<T1, T2, T3, T4, R>(
    source1: LiveData<T1>,
    source2: LiveData<T2>,
    source3: LiveData<T3>,
    source4: LiveData<T4>,
    combiner: (T1?, T2?, T3?, T4?) -> R?
) : MediatorLiveData<R>() {
    init {
        addSource(source1) {
            value = combiner(it, source2.value, source3.value, source4.value)
        }
        addSource(source2) {
            value = combiner(source1.value, it, source3.value, source4.value)
        }
        addSource(source3) {
            value = combiner(source1.value, source2.value, it, source4.value)
        }
        addSource(source4) {
            value = combiner(source1.value, source2.value, source3.value, it)
        }
    }
}

 fun functionName(): LiveData<XX> {
        return CombineLatestMediatorLiveDataOfFour(
           t1LiveData, t2LiveData,
            t3LiveData,  t4LiveData) { t1, t2, t3, t4->
                   XX
          }
     }

相关文章

网友评论

      本文标题:合并多个liveData

      本文链接:https://www.haomeiwen.com/subject/cfmtnctx.html