-1

I have multiple LiveData objects and would like to accumulate their contents inside a singular container.

How can I achieve this? An example in Java would be nice.

Edit: In the question suggested in the comments I see two different LiveData types. I'm interested in accumulating in a List data stored in multiple LiveData<Type> objects.

adriennoir
  • 1,329
  • 1
  • 15
  • 29
  • 1
    https://stackoverflow.com/questions/50599830/how-to-combine-two-live-data-one-after-the-other – coroutineDispatcher Sep 16 '19 at 12:50
  • 1
    Possible duplicate of [How to combine two live data one after the other?](https://stackoverflow.com/questions/50599830/how-to-combine-two-live-data-one-after-the-other) – Ikazuchi Sep 16 '19 at 13:00

1 Answers1

1

You should use Mediator Live data , should be something like :

fun <T1, T2, T3> combineLiveDatas(
        liveData1: LiveData<T1>,
        liveData2: LiveData<T2>,
        transform: (T1, T2) -> T3
): LiveData<T3> {
    return CombineLiveDatas(liveData1, liveData2, transform).result
}

private class CombineLiveDatas<T1, T2, T3>(
        liveData1: LiveData<T1>,
        liveData2: LiveData<T2>,
        private val transform: (T1, T2) -> T3
) {
    private var value1: T1? = liveData1.value
    private var value2: T2? = liveData2.value
    private val mediator = MediatorLiveData<T3>()
    val result: LiveData<T3> = mediator

    init {
        mediator.addSource(liveData1) { value ->
            value?.let {
                value1= it
                notifyDataChanged()
            }
        }
        mediator.addSource(liveData2) { value ->
            value?.let {
                value2= it
                notifyDataChanged()
            }
        }
        notifyDataChanged()
    }

    private fun notifyDataChanged() {
        val v1 = value1?: return
        val v2 = value2?: return
        mediator.value = transform(v1, v2)
    }
}
  • Thanks but my usecase is a bit different. I have identical types for the multiple LiveData objects which I want to accumulate in a single `List`. Do you know how to implement this in Java? – adriennoir Sep 16 '19 at 13:16