I've integrated the pagination component in my app and it's working perfectly fine (almost).
I've Database + network model. Database initially has some items which are consumed by LivePagedListBuilder
. I observe this LiveData<PagedList<InboxEntity>>
and ultimately feed the list to PagedListAdapter#submitList(PagedList<T> pagedList)
, something like :
LiveData<PagedList<Entity>> entities;
PagedList.Config pagedListConfig =
(new PagedList.Config.Builder()).setEnablePlaceholders(true)
.setPrefetchDistance(5)
.setEnablePlaceholders(false)
.setPageSize(10)
.setInitialLoadSizeHint(10)
.build();
entities = new LivePagedListBuilder<>(DAO.getItemList(), pagedListConfig)
entities.observe(this, new Observer<PagedList<Entity>>() {
@Override
public void onChanged(@Nullable PagedList<Entity> inboxEntities) {
inboxAdapter.submitList(inboxEntities);
isFirstLoad = false;
}
});
DAO#getItemList
returns DataSource.Factory<Integer, Entity>
.
I am listening for the boundary callback and trigger a network call when it reaches the end of the paged list. That call populates the database again.
There's one more thing. I've registered AdapterDataObserver
on recycler view because if an item has been inserted at the beginning, I've to scroll to the top position:
RecyclerView.AdapterDataObserver adapterDataObserver = new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if (positionStart == 0) {
layoutManager.scrollToPositionWithOffset(positionStart, 0);
}
}
};
I am facing a problem in this model :
After making the network call, database is populated again and onChanged
function is called with a new PagedList<Entity>
. Now, does this paged list contains only the new items. I've confirmed this.
But onItemRangeInserted
method is called with positionStart
as 0
too, which suggests that items are being inserted at the beginning. But they are not. They are being inserted at the end, confirmed with stetho db inspector.
Then why is the onItemRangeInserted
being called with positionStart
as 0
? This is making it difficult for me to distinguish when a fresh item is inserted at the beginning of the adapter and when items are inserted at the end.
Edit:
value of itemCount
is 10 which is my page size.
In DiffCallback, I just compare the primary key column of the two entities in areItemsTheSame
function.
if (positionStart == 0 && itemCount == 1) { layoutManager.scrollToPositionWithOffset(0, 0); }
– Mogador