2

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?

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Aleon Q
  • 336
  • 3
  • 8
  • Keeping track of the keys separately is the correct way to do it. Paging3 also doesn't have anything for this (although there are plans in the future). Note, you'll also need to handle request de-duplication in the event users scrolls up and down very quickly - this is handled for you in paging3 but not paging2. In terms of variable page size, although this is supported in v3, I'm not sure it would affect you because the terminal pages should be allowed to be arbitrary size IIRC. – dlam Dec 24 '20 at 19:15
  • Take a look into this example, instead of returning Datasource.Factory, returns a Listing of RedditPost, and in the parameters accepts the pagesize too. Here -> https://github.com/Sarah2402/android-architecture-components/blob/76366ce2d5e42fd38977570a6e75138061c3b95a/PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inDb/DbRedditPostRepository.kt#L104 – Felipe Malara Dec 26 '20 at 12:18

0 Answers0