LiveData分页列表大小始终为0 [英] LiveData Paged List size is always 0

查看:307
本文介绍了LiveData分页列表大小始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Android分页库实现了分页。 ViewModel返回 LiveData< PagedList< MyObject>> ,我观察到在设置适配器的片段中一切正常,除了想检查的地方列表的大小始终为0。

I implemented Paging using android paging library. The ViewModel returns a LiveData<PagedList<MyObject>> and I observe that in the fragment where I set the adapter and everything is working good, except that when I want to check the size of the list is always 0.

viewModel.getSearchResults().observe(this, mList -> {
           adapter.submitList(mList);
           Log.e("Count", String.valueOf(mList.size()));
       });

mList是 PagedList< MyObject>

推荐答案

如果您查看 PagedList 文档中的PagedList.html#loading-data rel = noreferrer>加载数据,您会注意到以下内容:

If you look at Loading Data from PagedList documentation you'll notice the following:


如果您使用 LivePagedListBuilder 来获取 LiveData< PagedList> ,它将为您在后台线程上初始化PagedLists。

If you use LivePagedListBuilder to get a LiveData<PagedList>, it will initialize PagedLists on a background thread for you.

此外,可变性和快照指出以下内容:

PagedList在加载时是可变的,或准备从其DataSource加载。随着加载成功,将通过主线程上的Runnables更新可变的PagedList。您可以使用 PagedList.Callback 收听这些更新。 (请注意, PagedListAdapter 会收听这些内容,以向RecyclerView发出有关更新/更改的信号。)

A PagedList is mutable while loading, or ready to load from its DataSource. As loads succeed, a mutable PagedList will be updated via Runnables on the main thread. You can listen to these updates with a PagedList.Callback. (Note that PagedListAdapter will listen to these to signal RecyclerView about the updates/changes).

如果您想听事件 onInserted onChanged onRemoved ,您可以执行以下操作:

If you want to listen for the events onInserted, onChanged or onRemoved you can do the following:

viewModel.observableData.observe(viewLifecycleOwner, Observer { pagedList ->
    adapter.submitList(pagedList)
    pagedList.addWeakCallback(null, object: PagedList.Callback() {
        override fun onChanged(position: Int, count: Int) {}
        override fun onInserted(position: Int, count: Int) {
            println("count: $count")
        }
        override fun onRemoved(position: Int, count: Int) {}
    })
})

这篇关于LiveData分页列表大小始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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