Refreshing MutableLiveData of list of items

怎甘沉沦 提交于 2019-12-03 16:34:38

问题


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

回答1:


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;



回答2:


According to MutableLiveData , you need to use postValue or setValue in order to trigger the observers.



来源:https://stackoverflow.com/questions/49246237/refreshing-mutablelivedata-of-list-of-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!