8

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>

max
  • 443
  • 7
  • 13

2 Answers2

13

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) {}
    })
})
Daniel
  • 400
  • 1
  • 2
  • 12
Rodrigo Queiroz
  • 2,674
  • 24
  • 30
  • 2
    I don't get any callbacks if the list size is in fact 0. I wanna show a no results message, any suggestions? – Ishaan Jul 11 '20 at 09:28
  • 1
    @Ishaan I would go for modelling the datasource to signal no results as separate object, it would be easier to manage: Consider sealed class ListItem{ data class Item(val model : Model) : ListItem() object NoResults: ListItem() } you could pass NoResults if your loadInitial return empty list of items – Lukas Sep 07 '20 at 07:41
  • This callback returns the pageSizeNumber only , how to return all list number ? – Ahmed Elsayed Sep 13 '20 at 07:15
0

If you use Rxjava3 ,

RxJava3CallAdapterFactory.create() , default is not synchronous.

You need to use RxJava3CallAdapterFactory.createSynchronous().

Zahra
  • 2,231
  • 3
  • 21
  • 41