LiveData Paged List size is always 0

…衆ロ難τιáo~ 提交于 2020-05-27 06:15:59

问题


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()));
       });

Where mList is a PagedList<MyObject>


回答1:


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

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

Also, Mutability and Snapshots states the following:

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).

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) {}
    })
})


来源:https://stackoverflow.com/questions/56742695/livedata-paged-list-size-is-always-0

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