How to remove an item from PagedListAdapter in Android Paging Component

phamxuanlu picture phamxuanlu · Aug 16, 2018 · Viewed 7.4k times · Source

I used Paging with Retrofit to loading list of Notifications data from REST API.

When I press delete button of a notification item then I call delete API to remove it. What is the proper way to remove it from PagedListAdapter after delete API response success? PagedList or PagedListAdapter does not support remove the item by index or object.

I tried to call DataSource.validate() but it reloads from begin, not from the current page.

Answer

jaychang0917 picture jaychang0917 · Aug 20, 2018

According to the official doc:

If you have more granular update signals, such as a network API signaling an update to a single item in the list, it's recommended to load data from network into memory. Then present that data to the PagedList via a DataSource that wraps an in-memory snapshot. Each time the in-memory copy changes, invalidate the previous DataSource, and a new one wrapping the new state of the snapshot can be created.

PagedList is immutable so you can't do any modifications against it. What you need to do is:

  1. maintain a mutable list L storing your server responses in your custom DataSource.
  2. pass it to LoadInitialCallback.onResult() (the PagedList is backing by L now).
  3. do whatever you like to L.
  4. call DataSource.invalidate() to pair with a new data source, so DataSource.loadInitial() is called to reflect the changes in step 3.