本文介绍了刷新项目列表的 MutableLiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用来自架构组件的 LiveData 和 ViewModel.

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.

是否可以让 LiveData 在后备列表更新时通知其观察者,而不仅仅是在 LiveData 对象更新时?

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)

这有效:

val results = MutableLiveData<MutableList<SearchResult>>()

/* later */

val list = mutableListOf<SearchResult>()
list.addAll(results.value)
list.addAll(newResults)
results.value = list

推荐答案

我觉得扩展更好一些.

operator fun <T> MutableLiveData<ArrayList<T>>.plusAssign(values: List<T>) {
    val value = this.value ?: arrayListOf()
    value.addAll(values)
    this.value = value
}

用法:

list += anotherList;

这篇关于刷新项目列表的 MutableLiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 14:01