Observe list of live data in java

2.5k Views Asked by At

I have a list of liveData, like List<LiveData<String>>. I want to observe this list so that whenever the String inside the LiveData changes, it would notify the observer of the list with this String.
How can I do this?
My list elements are strictly LiveData<String> so, it can not be simplified to String.
I know how to observe LiveData<String>, but not List<LiveData<String>>.
Please help.

Edit:

The element of the list is LiveData<String> because the String it is coming from the internet. So, list elements are holding object of LiveData<String>.

2

There are 2 best solutions below

2
On BEST ANSWER

If you want to observe a List<LiveData<String>>, you would have to attach an observer to each element of the list. The list itself is not observable, only each LiveData element of it. So, simply:

  1. Iterate the List
  2. Observe each LiveData element
  3. Decide what you want to do for each observed element
0
On

I know how to observe LiveData, but not List<LiveData>.

It's not that hard, all you need to do is swap the List<LiveData<String>> to become a LiveData<List<String>>.

For that, you can use MediatorLiveData.

fun <T> List<LiveData<T>>.combineList(): LiveData<List<T>> = MediatorLiveData<List<T>>().also { mediator ->
    val mutableList = this.map { it.value }.toMutableList()

    mediator.value = ArrayList(mutableList).toList()

    forEachIndexed { index, liveData ->
        addSource(liveData) { value
            mutableList[index] = value
            mediator.value = ArrayList(mutableList).toList()
        }
    }
}

Which should be observable with a single observer

strings.combineList().observe(viewLifecycleOwner) { listOfStrings -> ... }

All code is directly convertable to Java, nothing Kotlin-specific is used in this answer.