gpt4 book ai didi

android - LiveData 分页列表大小始终为 0

转载 作者:行者123 更新时间:2023-12-03 13:28:20 25 4
gpt4 key购买 nike

我使用 android 分页库实现了分页。 ViewModel 返回一个 LiveData<PagedList<MyObject>>我观察到在我设置适配器的 fragment 中,一切都运行良好,除了当我想检查列表的大小始终为 0 时。

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

其中 mList 是 PagedList<MyObject>

最佳答案

如果你看Loading Data来自 PagedList文档,您会注意到以下内容:

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



另外, Mutability and Snapshots声明如下:

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 , onChangedonRemoved您可以执行以下操作:
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) {}
})
})

关于android - LiveData 分页列表大小始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com