我有2个MutableLiveData。仅当两个MutableLiveData返回值时,才需要执行任务。在2 LiveData的情况下,我们可以使用MediatorLiveData进行相同的操作。就我而言,我正在使用MutableLiveData,它需要LiveData而不是MutableLiveData。
现在,仅当两个MutableLiveData的值都返回时,我才如何执行任务?
由于MediatorLiveData
从MutableLiveData
扩展,因此您仍然可以使用LiveData
。看看此链接,了解Marek Kondracki的答案How to combine two live data one after the other?:
val profile = MutableLiveData<ProfileData>()
val user = MutableLiveData<CurrentUser>()
val title = profile.combineWith(user) { profile, user ->
"${profile.job} ${user.name}"
}
fun <T, K, R> LiveData<T>.combineWith(
liveData: LiveData<K>,
block: (T?, K?) -> R
): LiveData<R> {
val result = MediatorLiveData<R>()
result.addSource(this) {
result.value = block.invoke(this.value, liveData.value)
}
result.addSource(liveData) {
result.value = block.invoke(this.value, liveData.value)
}
return result
}