My question is how to update item in PagedList?
In my case, there are ListActivity and DetailsActivity. List activity is using Paging component to get posts from network(only) and shows it in recycler view using paged adapter. When user is pressing on some post, I need to get post details and show it at the DetailsActivity. I am making another request to the server and it returns me post details. After that call, server increases viewsCount value of that post and when user returns to the posts list, I need to update that counter at the list item.
The question is, how to update single item (post), in that PagedList, cause I don't need to reload all list from the beginning just to update one single item.
PagedList is immutable
I would suggest you do not use the paging library because it assumes that your data is immutable which is almost impossible in a practical use-case.
You can check it in the official docs. It says:
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 the 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.
i.e.,
You have to fetch the data from the server and then store it into local DB using room library and then whenever you have to update any item, update the item into local DB and in turn room will reflect those changes into the UI(using LiveData).
But then you have to do the paging from using local DB.
In case of room, you'll have something like this.
@Dao
interface FeedDao {
@Query("SELECT * FROM feed ")
fun selectPaged(): DataSource.Factory<Int, Feed>
}
But then you have to take care of many more things like :
what if one entity gets deleted from the remote server. How are we going to notice that?
And we have to remove it from our local DB also.
You can read this article to solve this problem. It explains all the problems in paging library and a possible workaround if you really want to use the paging library.
My suggestion is to use this library and implement your own pagination.
PagedListAdapter
uses a DiffUtil.ItemCallback
that will only update an existing item if the it considers it a "new" item. It seems to me that you do need to go to the server in order to get the new view count, but also you do not want unaffected items to redraw. This can be prevented by adding the view count property to the DiffUtil.ItemCallback
to determine what a new item is. Items with a new view count will be redrawn, others won't.
I am assuming that the original request that retrieves the first list returns objects that have a viewsCount
field in them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With