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

问题描述 投票:2回答:1

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

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

android android-livedata
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.