问: 如果一个按钮状态被两个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
}
}
网友评论