Louis Gautier
05/31/2022, 7:01 PMfun <A, B>LiveData<A>.combine(
vararg other: LiveData<*>,
combiner: (/*Don't know*/) -> B
) {
val result = MediatorLiveData<B>()
other.forEach { liveData ->
result.addSource(liveData) {
if (other.toList().all { it.value != null }) {
result.postValue(combiner(other))
}
}
}
}
usage :
fun a() {
MutableLiveData<Int>().combine2(MutableLiveData<Boolean>()) { entry1, entry2, etc ->
}
}
Do you have any ideas ?Sam
05/31/2022, 7:38 PMLouis Gautier
05/31/2022, 7:42 PMLouis Gautier
05/31/2022, 7:45 PMFlow.combine
allow a two flows to be merged together. And what I’m looking for is exactly the same but with an indeterminate numbers of flow/LivedataFrancesc
05/31/2022, 10:47 PMLiveData
to a flow
with asFlow
and then use the combine
operatorephemient
06/01/2022, 3:53 AMprivate object Sentinel
fun <T> merge(vararg sources: LiveData<T>): LiveData<List<T>> {
val data = Array<Any?>(sources.size) { Sentinel }
val merged = MediatorLiveData<List<T>>()
sources.forEachIndexed { i, source ->
merged.addSource(source) { value ->
data[i] = value
if (data.all { it !== Sentinel }) {
merged.value = data.map { @Suppress("UNCHECKED_CAST") it as T }
}
}
}
return merged
}
merge(as, bs, cs).observe(lifecycle) { (a, b, c) -> ... }
or move the transform into the function using the same single-argument approach, but if you want to guarantee that as, bs, cs
match up with a, b, c
, you'd need separate overloads for each parameter list lengthLouis Gautier
06/01/2022, 3:03 PMFrancesc
06/01/2022, 3:46 PMFrancesc
06/01/2022, 3:49 PMdawidhyzy
10/31/2022, 12:56 PM