LiveData 分页列表大小始终为 0

LiveData Paged List size is always 0

我使用 android 分页库实现了分页。 ViewModel returns a LiveData<PagedList<MyObject>> 我观察到在我设置适配器的片段中一切正常,除了当我想检查列表的大小时总是 0。

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

其中 mList 是 PagedList<MyObject>

如果您查看 PagedList 文档中的 Loading Data,您会注意到以下内容:

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

如果您想监听事件 onInsertedonChangedonRemoved,您可以执行以下操作:

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

如果你使用 Rxjava3,

RxJava3CallAdapterFactory.create() ,默认不同步。

您需要使用RxJava3CallAdapterFactory.createSynchronous()