title: How to implement PagingSource.getRefreshKey for cursor based pagination - Android Jetpack Paging 3
body: <p>I am trying to implement cursor based pagination (based on <a href="https://relay.dev/graphql/connections.htm" rel="nofollow noreferrer">GraphQL Relay spec</a>) using <a href="https://developer.android.com/topic/libraries/architecture/paging/v3-overview" rel="nofollow noreferrer">Android Paging Library 3</a>, but I don't know how to implement <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingSource#getrefreshkey" rel="nofollow noreferrer"><code>getRefreshKey</code></a>.</p>
  <p>This is what I've tried:</p>
  <pre><code>data class PagingKey(
      val before: String? = null,
      val after: String? = null,
  )
  
  class MoviePagingSource() : PagingSource&lt;PagingKey, Movie&gt;() {
      override suspend fun load(params: LoadParams&lt;PagingKey&gt;): LoadResult&lt;PagingKey, Movie&gt; {
          return try {
              val response = fetchMovies(
                  before = params.key?.before,
                  after = params.key?.after,
                  pageSize = params.loadSize,
              )
  
              LoadResult.Page(
                  data = response.edges.map { mapEdgeToMovie(it) },
                  prevKey = if (response.pageInfo.hasPreviousPage) PagingKey(
                      before = response.pageInfo.startCursor
                  ) else null,
                  nextKey = if (response.pageInfo.hasNextPage) PagingKey(
                      after = response.pageInfo.endCursor
                  ) else null,
              )
          } catch (exception: Exception) {
              LoadResult.Error(exception)
          }
      }
  
      override fun getRefreshKey(state: PagingState&lt;PagingKey, Movie&gt;): PagingKey? {
          // TODO: What to return here?
      }
  }
  </code></pre>
  <p>In all the examples I could find a page number is simply incremented/decremented, but that doesn't work with cursors.</p>
  <p>What is the proper way to implement this?</p>
  <hr />
  <p><em>Before this gets incorrectly marked as a duplicate, I've already seen <a href="https://stackoverflow.com/q/66979100/4136777">this question</a>. This does not answer my question because their API is called as <code>service.getOrders(query, params.key ?: &quot;&quot;, 10)</code> instead of the separate <code>before</code>/<code>after</code> arguments like <code>fetchMovies</code> above.</em></p>