如何观察何时返回2 MutableLiveData中的值?

时间:2019-12-27 17:08:28

标签: android android-livedata

我有2个MutableLiveData。仅当两个MutableLiveData返回值时,才需要执行任务。 如果是2个 LiveData ,我们可以使用MediatorLiveData进行相同的操作。就我而言,我使用的是 MutableLiveData ,它需要LiveData而不是MutableLiveData。

现在,仅当两个MutableLiveData中的值都返回时,我才如何执行任务?

1 个答案:

答案 0 :(得分:0)

由于MediatorLiveDataMutableLiveData扩展,因此您仍然可以使用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
}