刷新项目列表的MutableLiveData [英] Refreshing MutableLiveData of list of items

查看:780
本文介绍了刷新项目列表的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>>

当我执行初始加载并将变量设置为新列表时,它将触发绑定适配器上的回调,该回调将数据加载到recyclerview中.

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?

这不起作用(忽略null检查):

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

推荐答案

我认为扩展名更好一些.

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
}

用法:

list += anotherList;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆