Paging 3

Learn Android Paging 3 with Kotlin and Jetpack Compose to master PagingSource, Pager, RemoteMediator, LoadState, and offline-first data with Room. About 28 minutes.

Why it matters

  • Feeds, search results and chat histories are too long to load at once. Paging 3 loads pages as the user scrolls, keeps memory bounded and handles retries and loading states for you.
  • Getting the keys wrong produces duplicated or missing items; getting getRefreshKey wrong makes the list jump to the top after every refresh.
  • Senior interviews probe RemoteMediator with Room, LoadType, getRefreshKey, and how LoadState drives loading, error and empty UI.
  • Paging 3 is where the Room and repository lessons meet: a RemoteMediator writes pages into Room, Room's PagingSource reads them, and the UI never talks to the network.

The simple explanation

  • You read a long book through a librarian. You never carry the whole book.
  • Each time you near the end of your pages, you ask for the next chunk: that is one PagingSource.load call, and the bookmark you hand over is the key.
  • If the librarian has to reprint the book (the data changed), they ask where you were so they can start there: that is getRefreshKey.
  • In the offline-first setup you read from your own photocopies (Room). When you run low, an assistant fetches more pages from the archive and adds them to your pile: that is the RemoteMediator.

The pieces.

  • PagingSource<Key, Value> loads one page for a key. load(params) returns LoadResult.Page(data, prevKey, nextKey), LoadResult.Error(throwable) for a failure the user can retry, or LoadResult.Invalid() when the source is out of date and must be replaced. A null prevKey or nextKey means there is nothing more in that direction.
  • A PagingSource is a snapshot. When the data changes it is invalidated, and Pager calls pagingSourceFactory again for a new one. Room's generated PagingSource invalidates itself when its tables change.
  • getRefreshKey(state) is abstract, so every source implements it. It returns the key to load first in the new source, normally derived from state.anchorPosition (the most recently accessed index), so the list stays where the user was.
  • Pager(config, remoteMediator, pagingSourceFactory).flow produces Flow<PagingData<T>>. PagingConfig sets pageSize, prefetchDistance (defaults to pageSize), initialLoadSize (defaults to three times pageSize), enablePlaceholders and an optional maxSize that drops pages far from the viewport.
  • cachedIn(viewModelScope) shares the loaded pages, so a configuration change or a second collector gets them without reloading. A PagingData must not be collected more than once without it.
  • In Compose, collectAsLazyPagingItems() gives LazyPagingItems with itemCount, get(index) (which also triggers loading), loadState, retry() and refresh(). With RecyclerView you use PagingDataAdapter.

RemoteMediator. For network plus database, you pass a RemoteMediator to the Pager and use Room's PagingSource as the factory. load(loadType, state) is called with LoadType.REFRESH (start or user refresh), APPEND (reached the end of the cached data) or PREPEND (reached the start). It fetches a page, writes it to Room in a transaction (clearing old rows on REFRESH), and returns MediatorResult.Success(endOfPaginationReached) or MediatorResult.Error(throwable). Room invalidates its PagingSource, which reloads from the database. initialize() can return SKIP_INITIAL_REFRESH to show the cache without fetching on start.

ComponentRole
PagingSourceLoads one page for a key; one instance per snapshot of the data
getRefreshKeyPicks the first key for the next source so the scroll position survives
Pager + PagingConfigCreates sources, decides when to load and how much
RemoteMediatorFetches from the network and writes into Room
cachedIn(viewModelScope)Shares loaded pages across collectors and configuration changes
collectAsLazyPagingItemsTurns the flow into items and load states for LazyColumn
LoadStateLoading, NotLoading(endOfPaginationReached) or Error for refresh, append and prepend
How the next page gets loaded
How the next page gets loaded The user scrolls near the end of the LazyColumn. The Pager calls load on the PagingSource with the next key. The PagingSource returns a page of items and the key after it. The Pager emits new PagingData, which the list collects with collectAsLazyPagingItems and shows. The new items appear in the list NEAR THE END load(nextKey) Page(items, nextKey) NEW PagingData LazyColumn LazyPagingItems Pager PagingData PagingSource loads pages
The list asks for more as the user nears the end; the Pager calls load with the next key and a new PagingData flows back.

Notes

  • LoadResult has three cases: Page, Error and Invalid. Return Error for network or HTTP failures; the UI calls retry().
  • MediatorResult has two: Success(endOfPaginationReached) and Error(throwable).
  • RemoteMediator.load(loadType, state) gets no key argument. You derive the next key from state (for example state.lastItemOrNull()) or from a remote-keys table you store in Room.
  • The first load asks for initialLoadSize, three times pageSize by default. With a page-number API, do not pass params.loadSize as the page size, or page 2 overlaps page 1; use a fixed page size or set initialLoadSize = pageSize.
  • pagingSourceFactory must return a new instance every time. Returning the same instance after it was invalidated throws.
  • Apply map or filter on PagingData before cachedIn, so the work is cached too. For a search query, use flatMapLatest on the query flow to build a new Pager, then cachedIn.
  • cachedIn needs a scope that outlives configuration changes but not the screen, which is viewModelScope. Calling it in a composable or on every recomposition starts a new cache each time.
  • loadState.refresh, append and prepend combine the source and the mediator. Use loadState.mediator?.refresh to tell "network refresh failed" from "database is loading".
  • Show an empty state only when loadState.refresh is LoadState.NotLoading and itemCount == 0; while refresh is Loading, show a spinner instead.
  • Give LazyColumn stable keys with items.itemKey { it.id }, so items keep their state when pages are inserted.

Code example

An offline-first feed: a RemoteMediator writes pages into Room, Room's generated PagingSource feeds the Pager, the ViewModel caches the flow and Compose renders items and load states. A network-only PagingSource with page numbers follows, to show getRefreshKey.

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.paging.map
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import androidx.room.withTransaction
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import retrofit2.HttpException
 
@Entity(tableName = "articles")
data class ArticleEntity(@PrimaryKey val id: Long, val title: String)
 
@Dao
interface ArticleDao {
    // Room generates the PagingSource and invalidates it when the table changes (room-paging)
    @Query("SELECT * FROM articles ORDER BY id ASC")
    fun pagingSource(): PagingSource<Int, ArticleEntity>
 
    @Upsert
    suspend fun upsertAll(items: List<ArticleEntity>)
 
    @Query("DELETE FROM articles")
    suspend fun clearAll()
}
 
@OptIn(ExperimentalPagingApi::class)
class ArticleRemoteMediator(
    private val db: AppDb,          // RoomDatabase with articles(): ArticleDao
    private val api: ArticleApi,    // suspend fun articles(afterId: Long?, limit: Int): List<ArticleDto>
) : RemoteMediator<Int, ArticleEntity>() {
 
    override suspend fun load(loadType: LoadType, state: PagingState<Int, ArticleEntity>): MediatorResult {
        val afterId: Long? = when (loadType) {
            LoadType.REFRESH -> null
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            LoadType.APPEND -> state.lastItemOrNull()?.id
                ?: return MediatorResult.Success(endOfPaginationReached = true)
        }
        return try {
            val page = api.articles(afterId = afterId, limit = state.config.pageSize)
            db.withTransaction {
                if (loadType == LoadType.REFRESH) db.articles().clearAll()
                db.articles().upsertAll(page.map { ArticleEntity(it.id, it.title) })
            }
            MediatorResult.Success(endOfPaginationReached = page.isEmpty())
        } catch (e: IOException) {
            MediatorResult.Error(e)
        } catch (e: HttpException) {
            MediatorResult.Error(e)
        }
    }
}
 
class ArticleRepository(private val db: AppDb, private val api: ArticleApi) {
    @OptIn(ExperimentalPagingApi::class)
    fun feed(): Flow<PagingData<Article>> =
        Pager(
            config = PagingConfig(pageSize = 20),
            remoteMediator = ArticleRemoteMediator(db, api),
            pagingSourceFactory = { db.articles().pagingSource() }, // a new source every time
        ).flow.map { paging -> paging.map { Article(it.id, it.title) } }
}
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import kotlinx.coroutines.flow.Flow
 
class FeedViewModel(repository: ArticleRepository) : ViewModel() {
    // Transform first, then cache: survives rotation and is collected only through this cache
    val feed: Flow<PagingData<Article>> = repository.feed().cachedIn(viewModelScope)
}
 
@Composable
fun FeedScreen(viewModel: FeedViewModel) {
    val items = viewModel.feed.collectAsLazyPagingItems()
    val refresh = items.loadState.refresh
 
    when {
        refresh is LoadState.Loading && items.itemCount == 0 -> CircularProgressIndicator()
        refresh is LoadState.Error && items.itemCount == 0 ->
            Button(onClick = { items.retry() }) { Text("Could not load. Retry") }
        refresh is LoadState.NotLoading && items.itemCount == 0 -> Text("No articles yet")
        else -> LazyColumn {
            items(count = items.itemCount, key = items.itemKey { it.id }) { index ->
                val article = items[index] // also tells Paging which index is being viewed
                Text(article?.title ?: "Loading...") // null is a placeholder
            }
            when (items.loadState.append) {
                is LoadState.Loading -> item { CircularProgressIndicator() }
                is LoadState.Error -> item { Button(onClick = { items.retry() }) { Text("Retry") } }
                is LoadState.NotLoading -> Unit
            }
        }
    }
}

A network-only source with page numbers, for a search screen that does not need offline support:

class SearchPagingSource(
    private val api: ArticleApi,   // suspend fun search(query: String, page: Int, pageSize: Int): List<ArticleDto>
    private val query: String,
) : PagingSource<Int, ArticleDto>() {
 
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleDto> {
        val page = params.key ?: 1
        return try {
            // Fixed page size: params.loadSize is larger on the first load and would break page math
            val items = api.search(query, page = page, pageSize = PAGE_SIZE)
            LoadResult.Page(
                data = items,
                prevKey = if (page == 1) null else page - 1,
                nextKey = if (items.size < PAGE_SIZE) null else page + 1,
            )
        } catch (e: IOException) {
            LoadResult.Error(e)
        } catch (e: HttpException) {
            LoadResult.Error(e)
        }
    }
 
    // Find the page around the last viewed position and reload that page number
    override fun getRefreshKey(state: PagingState<Int, ArticleDto>): Int? =
        state.anchorPosition?.let { anchor ->
            val anchorPage = state.closestPageToPosition(anchor)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
 
    companion object { const val PAGE_SIZE = 20 }
}
  • The mediator never returns items to the UI; it writes to Room, Room invalidates its PagingSource, and the new source reads the updated table. Room is the single source of truth.
  • LoadType.PREPEND returns end-of-pagination at once because this feed only grows at the end. APPEND uses the last item in the loaded pages as the cursor.
  • prevKey + 1 and nextKey - 1 recover the anchor page's own number, because a page does not store its key.
  • Placeholders are on by default with Room's source, so items[index] can be null while a page loads.

Run the idea in plain Kotlin

A plain-Kotlin model of a page-number PagingSource: keys chain from page to page, nextKey = null ends the list, and getRefreshKey turns an anchor position into the page to reload.

import kotlinx.coroutines.*

data class Page(val data: List<Int>, val prevKey: Int?, val nextKey: Int?)

class NumbersSource(private val total: Int, private val pageSize: Int) {
  suspend fun load(key: Int?): Page {
      val page = key ?: 1
      delay(10) // network call
      val start = (page - 1) * pageSize
      val data = (start until minOf(start + pageSize, total)).toList()
      return Page(
          data = data,
          prevKey = if (page == 1) null else page - 1,
          nextKey = if (data.size < pageSize) null else page + 1,
      )
  }

  // Same idea as PagingState.closestPageToPosition, then prevKey + 1 or nextKey - 1
  fun getRefreshKey(pages: List<Page>, anchorPosition: Int): Int? {
      var index = anchorPosition
      for (p in pages) {
          if (index < p.data.size) return p.prevKey?.plus(1) ?: p.nextKey?.minus(1)
          index -= p.data.size
      }
      return null
  }
}

fun main() = runBlocking {
  val source = NumbersSource(total = 45, pageSize = 20)
  val pages = mutableListOf<Page>()
  var key: Int? = null
  do {
      val page = source.load(key)
      pages.add(page)
      println("loaded key=" + (key ?: 1) + " items " + page.data.first() + ".." + page.data.last() + " next=" + page.nextKey)
      key = page.nextKey
  } while (key != null)

  println("total items: " + pages.sumOf { it.data.size })
  println("refresh key for anchor 25: " + source.getRefreshKey(pages, 25))
  println("refresh key for anchor 44: " + source.getRefreshKey(pages, 44))
}

Expected output:

loaded key=1 items 0..19 next=2
loaded key=2 items 20..39 next=3
loaded key=3 items 40..44 next=null
total items: 45
refresh key for anchor 25: 2
refresh key for anchor 44: 3

In production

List jumps to the top after every like
  • A network-backed PagingSource called invalidate() after the user liked a post, so the like count would refresh.
  • Its getRefreshKey returned null, so each new source started again from page 1.
  • Users scrolled 200 items down, tapped like, and landed back at the top.
The fix
  • Implemented getRefreshKey from state.anchorPosition with closestPageToPosition, returning prevKey + 1 or nextKey - 1.
  • Moved the feed to a RemoteMediator with Room, and stored likes as a Room update, so only the affected rows change and Room's source keeps the position.
  • Added a test with TestPager that loads three pages, builds the state with an anchor in page 3, and asserts the refresh key.
Duplicated items in search results
  • Search results repeated items 21 to 40 right after the first screen of results.
  • The PagingSource passed params.loadSize as the API's page size. The first load used initialLoadSize (60 by default for pageSize = 20), so "page 1" returned 60 items, and the next load asked for page 2 of size 20, which is items 21 to 40 again.
  • Because the list used itemKey, LazyColumn then crashed with a duplicate-key IllegalArgumentException.
The fix
  • Sent a fixed PAGE_SIZE to the API regardless of loadSize. (Setting initialLoadSize = pageSize, or switching to offset keys, also works.)
  • Added a PagingSource unit test that loads the first two pages and asserts no ids repeat.
  • Kept stable keys in LazyColumn; the crash had exposed the real bug instead of hiding it.

Common mistakes

  • Returning null from getRefreshKey without thinking. After any invalidation the new source starts from the beginning and the list jumps to the top. Derive the key from state.anchorPosition.
  • Using params.loadSize as the API page size with page-number keys. The first load is larger, so pages overlap. Use a fixed page size, or offset keys.
  • Skipping cachedIn(viewModelScope). After rotation the list reloads from scratch, and collecting the same PagingData twice throws. Apply transformations, then cachedIn in the ViewModel.
  • Returning the same PagingSource instance from the factory. An invalidated source cannot be reused; the factory must create a new one each time.
  • Fetching from the network inside a Room-backed setup's PagingSource. Let the RemoteMediator write to Room and let Room's source read it. Mixing both gives two sources of truth and duplicated pages.
  • Ignoring LoadState. Without it, a failed first load is a blank screen and a failed append is a list that silently stops. Render refresh and append loading, error with retry(), and the empty state.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Explain how PagingSource works and what getRefreshKey does.”

“How does RemoteMediator integrate with Paging 3?”

“What does cachedIn do, and what goes wrong without it?”

“How do you render loading, error and empty states with Paging?”

Quiz

Which values can PagingSource.load return?

A page-number PagingSource sends params.loadSize to the API as the page size, with PagingConfig(pageSize = 20). What goes wrong?

In a RemoteMediator, what should load return when the network request throws an IOException?

Why apply cachedIn(viewModelScope) to the Pager flow in the ViewModel?

0 of 4 answered

Mini task

15-minute exercise: an offline-first paged feed

  1. Add paging-runtime, paging-compose and room-paging. In your DAO, add @Query("SELECT * FROM articles ORDER BY id ASC") fun pagingSource(): PagingSource<Int, ArticleEntity>.
  2. Write an ArticleRemoteMediator that clears and inserts on REFRESH, returns Success(endOfPaginationReached = true) for PREPEND, uses state.lastItemOrNull()?.id as the cursor for APPEND, and returns MediatorResult.Error for IOException and HttpException.
  3. In the repository, build Pager(PagingConfig(pageSize = 20), remoteMediator = ..., pagingSourceFactory = { dao.pagingSource() }).flow, mapped to a domain model.
  4. In the ViewModel, expose repository.feed().cachedIn(viewModelScope).
  5. In Compose, call collectAsLazyPagingItems(), use items.itemKey { it.id }, and render: a spinner for the first load, a full-screen retry when refresh fails with no items, an empty state, and a footer spinner or retry button for append.
  6. Turn on airplane mode, relaunch, and check that the cached pages still show with an error message instead of a blank screen.

Done condition: scrolling loads more pages without duplicates, rotating keeps the position and does not reload, and the feed works offline from Room.

Next: Retrofit and OkHttp