gpt4 book ai didi

java - 如何使用 LiveData 实现 zip 功能

转载 作者:行者123 更新时间:2023-12-04 23:52:18 25 4
gpt4 key购买 nike

我正在使用两个 LiveDatas 从我的服务器获取数据,并希望在两个 LiveData 完成后得到结果?

LiveData live1 = ...;
LiveData live2 = ...;
MutableLiveData live3 = ...;

live1.observe(this, value -> {
live3.postValue(value);
});

live2.observe(this, value -> {
live3.postValue(value);
});

live3.observe(this, value -> {
// TODO: Get both values from live1, live2
}

我期望 live1 和 live2 的两个值

最佳答案

你需要的是zip功能:

fun <A, B> zip(first: LiveData<A>, second: LiveData<B>): LiveData<Pair<A, B>> {
val mediatorLiveData = MediatorLiveData<Pair<A, B>>()

var isFirstEmitted = false
var isSecondEmitted = false
var firstValue: A? = null
var secondValue: B? = null

mediatorLiveData.addSource(first) {
isFirstEmitted = true
firstValue = it
if (isSecondEmitted) {
mediatorLiveData.value = Pair(firstValue!!, secondValue!!)
isFirstEmitted = false
isSecondEmitted = false
}
}
mediatorLiveData.addSource(second) {
isSecondEmitted = true
secondValue = it
if (isFirstEmitted) {
mediatorLiveData.value = Pair(firstValue!!, secondValue!!)
isFirstEmitted = false
isSecondEmitted = false
}
}

return mediatorLiveData
}



现在,您可以调用 zip(firstLiveData,secondLiveData)并观察它。

关于java - 如何使用 LiveData 实现 zip 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com