Android paging2 library: Network(PageKeyedDataSource) + Database idiomatic/expected way to implement

233 views Asked by At

I'm not considering Paging3 since it is still in alpha as of now, So, any suggestions on implementing this using paging 3 are definitely welcome but won't be much useful in context.

From the paging 2 (db+network)sample:

RedditPostDao.postsBySubreddit() returns DataSource.Factory

fun postsBySubreddit(subreddit: String): DataSource.Factory<Int, RedditPost>

Which is used with SubRedditBoundaryCallback to create LiveData of PagedList of RedditPost

SubRedditBoundaryCallback has onItemAtEndLoaded(itemAtEnd: RedditPost) {…}

Which gets called when DB can no longer provide further items. This works well in this case as the reddit API used is ItemKeyed like.

My question is: How do I use the paging 2 with Network + Database if my web API is PageKeyed. I would need the nextPageLink to make the network call from the BoundaryCallback's onItemAtEndLoaded() but this method returns the last item and doesn't have any information on next page link.

Here is how I did it to make it work with page keys. The following implementation works but I wanted to see if there is more idiomatic/expected way of doing this.

I created another Room table for Entity:

RedditPostPageLink(redditPostName: String, nextPageKey: String)

When I receive the data from the network API, I pick up the last item in the response and make and entry in the RedditPostPageLink(name, nextPageKey).

In the BoundaryCallback. onItemAtEndLoaded(), when I get and itemAtEnd, I get the corresponding nextPageKey that I had earlier stored and make a web API call based on that.

Given that page sizes are pretty much fixed, is there a better version to achieve this with paging 2?

0

There are 0 answers