You are viewing documentation for a preview version of this software.

Learn about previews.

Managing pagination manually


Using the ApolloStore APIs, you can update the cache manually whenever you fetch a new page of data.

Here's a general outline of how you can do this:

Kotlin
1suspend fun fetchAndMergePage(nextPage: Int) {
2  // 1. Get the current list from the cache
3  val listQuery = UsersPageQuery(page = 1)
4  val cacheResponse = apolloClient.query(listQuery).fetchPolicy(FetchPolicy.CacheOnly).execute()
5
6  // 2. Fetch the next page from the network (don't update the cache yet)
7  val networkResponse = apolloClient.query(UsersPageQuery(page = nextPage)).fetchPolicy(FetchPolicy.NetworkOnly).execute()
8
9  // 3. Merge the next page with the current list
10  val mergedList = cacheResponse.data.usersPage.items + networkResponse.data.usersPage.items
11  val dataWithMergedList = networkResponse.data.copy(
12    usersPage = networkResponse.data.usersPage.copy(
13      items = mergedList
14    )
15  )
16
17  // 4. Update the cache with the merged list
18  val keys = apolloClient.apolloStore.writeOperation(operation = listQuery, operationData = dataWithMergedList)
19  apolloClient.apolloStore.publish(keys)
20}

Note that in this simple example, we need to remember the last fetched page, so we can know which page to fetch next. This can be stored in shared preferences for instance. However in most cases the API can return a "page info" object containing the information needed to fetch the next page, and this can be stored in the cache with the rest of the data.

An example of doing this is available here.

Feedback

Edit on GitHub

Ask Community