7. Paginate results


As you might have noticed, the object returned from the LaunchListQuery is a LaunchConnection. This object has a list of launches, a pagination cursor, and a boolean to indicate whether more launches exist.

When using a cursor-based pagination system, it's important to remember that the cursor gives you a place where you can get all results after a certain spot, regardless of whether more items have been added in the interim.

In the previous section, you hardcoded the SMALL size argument directly in the GraphQL query, but you can also define arguments programmatically using variables. You will use them here to implement pagination.

add a cursor variable

In LaunchList.graphql, add a cursor variable. In GraphQL, variables are prefixed with the dollar sign, like so:

GraphQL
app/src/main/graphql/com/example/rocketreserver/LaunchList.graphql
1query LaunchList($cursor: String) {
2  launches(after: $cursor) {
3    cursor
4    hasMore
5    launches {
6      id
7      site
8      mission {
9        name
10        missionPatch(size: SMALL)
11      }
12    }
13  }
14}

You can experiment with GraphQL variables in GraphQL Playground by using the lower-left pane named Query variables. If you omit the $cursor variable, the server returns data starting from the beginning.

GraphQL Playground variables

Get a callback when more data is needed

modify LaunchListAdapter.kt to get a callback when the end of the list is reached:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListAdapter.kt
1    var onEndOfListReached: (() -> Unit)? = null
2
3    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
4        val launch = launches.get(position)
5        // ...
6
7        if (position == launches.size - 1) {
8            onEndOfListReached?.invoke()
9        }
10    }
11

Note that you can add some look-ahead and trigger the callback before the end of list is reached if you want to minimize the wait time and trigger a new network requests a few items before the end of list is reached. This is a basic implementation of a paging adapter - in a real project you would probably use something like the Jetpack Paging library.

Connect to the callback

In LaunchListFragment.kt, register this callback and link it to a coroutine Channel:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListFragment.kt
1        val launches = mutableListOf<LaunchListQuery.Launch>()
2        val adapter = LaunchListAdapter(launches)
3        binding.launches.layoutManager = LinearLayoutManager(requireContext())
4        binding.launches.adapter = adapter
5
6        val channel = Channel<Unit>(Channel.CONFLATED)
7
8        // Send a first item to do the initial load else the list will stay empty forever
9        channel.trySend(Unit)
10        adapter.onEndOfListReached = {
11            channel.trySend(Unit)
12        }

Channels are useful for communicating between coroutines. In this case, the channel does not transfer any real data besides the information that the end of list has been reached. For this it uses the Unit data type. Every time a Unit object is read from the channel, it means the adapter might need more data.

Also note that the channel is CONFLATED. A conflated channel will drop items if the consumer cannot proceed through them fast enough. In this case, if the user scrolls up and down while a query is still in flight, you don't want to buffer these requests to replay them later, so it's fine to drop them.

Execute the paginated query

Start a coroutine and execute the query. Replace the previous single query with the paginated version:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListFragment.kt
1  lifecycleScope.launchWhenResumed {
2      var cursor: String? = null
3      for (item in channel) {
4          val response = try {
5              apolloClient.query(LaunchListQuery(cursor = Input.fromNullable(cursor))).await()
6          } catch (e: ApolloException) {
7              Log.d("LaunchList", "Failure", e)
8              return@launchWhenResumed
9          }
10
11          val newLaunches = response.data?.launches?.launches?.filterNotNull()
12
13          if (newLaunches != null) {
14              launches.addAll(newLaunches)
15              adapter.notifyDataSetChanged()
16          }
17
18          cursor = response.data?.launches?.cursor
19          if (response.data?.launches?.hasMore != true) {
20              break
21          }
22      }
23
24      adapter.onEndOfListReached = null
25      channel.close()
26  }

Coroutines help you write pagination as if it were a procedural while loop. Notice how the cursor is updated at each iteration and the loop is terminated if there is no data to get from the backend anymore (hasMore == false)

Test scrolling

Click Run. You can now see all the scheduled launches!

Next, you'll add a details view that will allow you to book a seat on a launch.

Feedback

Edit on GitHub

Forums