Paging 3
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
getRefreshKeywrong makes the list jump to the top after every refresh. - Senior interviews probe
RemoteMediatorwith Room,LoadType,getRefreshKey, and howLoadStatedrives loading, error and empty UI. - Paging 3 is where the Room and repository lessons meet: a
RemoteMediatorwrites pages into Room, Room'sPagingSourcereads 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.loadcall, 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)returnsLoadResult.Page(data, prevKey, nextKey),LoadResult.Error(throwable)for a failure the user can retry, orLoadResult.Invalid()when the source is out of date and must be replaced. AnullprevKeyornextKeymeans there is nothing more in that direction.- A
PagingSourceis a snapshot. When the data changes it is invalidated, andPagercallspagingSourceFactoryagain for a new one. Room's generatedPagingSourceinvalidates 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 fromstate.anchorPosition(the most recently accessed index), so the list stays where the user was.Pager(config, remoteMediator, pagingSourceFactory).flowproducesFlow<PagingData<T>>.PagingConfigsetspageSize,prefetchDistance(defaults topageSize),initialLoadSize(defaults to three timespageSize),enablePlaceholdersand an optionalmaxSizethat drops pages far from the viewport.cachedIn(viewModelScope)shares the loaded pages, so a configuration change or a second collector gets them without reloading. APagingDatamust not be collected more than once without it.- In Compose,
collectAsLazyPagingItems()givesLazyPagingItemswithitemCount,get(index)(which also triggers loading),loadState,retry()andrefresh(). With RecyclerView you usePagingDataAdapter.
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.
| Component | Role |
|---|---|
PagingSource | Loads one page for a key; one instance per snapshot of the data |
getRefreshKey | Picks the first key for the next source so the scroll position survives |
Pager + PagingConfig | Creates sources, decides when to load and how much |
RemoteMediator | Fetches from the network and writes into Room |
cachedIn(viewModelScope) | Shares loaded pages across collectors and configuration changes |
collectAsLazyPagingItems | Turns the flow into items and load states for LazyColumn |
LoadState | Loading, NotLoading(endOfPaginationReached) or Error for refresh, append and prepend |
Notes
LoadResulthas three cases:Page,ErrorandInvalid. ReturnErrorfor network or HTTP failures; the UI callsretry().MediatorResulthas two:Success(endOfPaginationReached)andError(throwable).RemoteMediator.load(loadType, state)gets no key argument. You derive the next key fromstate(for examplestate.lastItemOrNull()) or from a remote-keys table you store in Room.- The first load asks for
initialLoadSize, three timespageSizeby default. With a page-number API, do not passparams.loadSizeas the page size, or page 2 overlaps page 1; use a fixed page size or setinitialLoadSize = pageSize. pagingSourceFactorymust return a new instance every time. Returning the same instance after it was invalidated throws.- Apply
maporfilteronPagingDatabeforecachedIn, so the work is cached too. For a search query, useflatMapLateston the query flow to build a newPager, thencachedIn. cachedInneeds a scope that outlives configuration changes but not the screen, which isviewModelScope. Calling it in a composable or on every recomposition starts a new cache each time.loadState.refresh,appendandprependcombine the source and the mediator. UseloadState.mediator?.refreshto tell "network refresh failed" from "database is loading".- Show an empty state only when
loadState.refresh is LoadState.NotLoadinganditemCount == 0; while refresh isLoading, show a spinner instead. - Give
LazyColumnstable keys withitems.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.PREPENDreturns end-of-pagination at once because this feed only grows at the end.APPENDuses the last item in the loaded pages as the cursor.prevKey + 1andnextKey - 1recover 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 benullwhile 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
- A network-backed
PagingSourcecalledinvalidate()after the user liked a post, so the like count would refresh. - Its
getRefreshKeyreturnednull, so each new source started again from page 1. - Users scrolled 200 items down, tapped like, and landed back at the top.
- Implemented
getRefreshKeyfromstate.anchorPositionwithclosestPageToPosition, returningprevKey + 1ornextKey - 1. - Moved the feed to a
RemoteMediatorwith 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
TestPagerthat loads three pages, builds the state with an anchor in page 3, and asserts the refresh key.
- Search results repeated items 21 to 40 right after the first screen of results.
- The
PagingSourcepassedparams.loadSizeas the API's page size. The first load usedinitialLoadSize(60 by default forpageSize = 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,LazyColumnthen crashed with a duplicate-keyIllegalArgumentException.
- Sent a fixed
PAGE_SIZEto the API regardless ofloadSize. (SettinginitialLoadSize = pageSize, or switching to offset keys, also works.) - Added a
PagingSourceunit 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
nullfromgetRefreshKeywithout thinking. After any invalidation the new source starts from the beginning and the list jumps to the top. Derive the key fromstate.anchorPosition. - Using
params.loadSizeas 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 samePagingDatatwice throws. Apply transformations, thencachedInin the ViewModel. - Returning the same
PagingSourceinstance 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 theRemoteMediatorwrite 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 withretry(), 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
- Add
paging-runtime,paging-composeandroom-paging. In your DAO, add@Query("SELECT * FROM articles ORDER BY id ASC") fun pagingSource(): PagingSource<Int, ArticleEntity>. - Write an
ArticleRemoteMediatorthat clears and inserts onREFRESH, returnsSuccess(endOfPaginationReached = true)forPREPEND, usesstate.lastItemOrNull()?.idas the cursor forAPPEND, and returnsMediatorResult.ErrorforIOExceptionandHttpException. - In the repository, build
Pager(PagingConfig(pageSize = 20), remoteMediator = ..., pagingSourceFactory = { dao.pagingSource() }).flow, mapped to a domain model. - In the ViewModel, expose
repository.feed().cachedIn(viewModelScope). - In Compose, call
collectAsLazyPagingItems(), useitems.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. - 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.