I'm using LiveData and ViewModel from the architecture components in my app.
I have a list of items that is paginated, I load more as the user scrolls down. The result of the query is stored in a
MutableLiveData<List<SearchResult>>
When I do the initial load and set the variable to a new list, it triggers a callback on the binding adapter that loads the data into the recyclerview.
However, when I load the 2nd page and I add the additional items to the list, the callback is not triggered. However, if I replace the list with a new list containing both the old and new items, the callback triggers.
Is it possible to have LiveData notify its observers when the backing list is updated, not only when the LiveData object is updated?
This does not work (ignoring the null checks):
val results = MutableLiveData<MutableList<SearchResult>>()
/* later */
results.value.addAll(newResults)
This works:
val results = MutableLiveData<MutableList<SearchResult>>()
/* later */
val list = mutableListOf<SearchResult>()
list.addAll(results.value)
list.addAll(newResults)
results.value = list
I think the extension is a bit nicer.
operator fun <T> MutableLiveData<ArrayList<T>>.plusAssign(values: List<T>) {
val value = this.value ?: arrayListOf()
value.addAll(values)
this.value = value
}
Usage:
list += anotherList;