Skip to content
Commitwise
Menu
Android Development

Paging 3 and DataStore

Load long lists page by page with Paging 3 (PagingSource, Pager, cachedIn, LazyPagingItems and load states), build an offline-first feed with Room and a RemoteMediator, and replace SharedPreferences with DataStore without the classic mistakes: duplicate instances, blocking reads and lost updates.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The order history screen loads all of a customer’s orders at once. For most people that’s fine; for the restaurant chain with 40,000 orders it takes eight seconds and sometimes runs out of memory. After a rotation the list reloads from the start. And the settings screen reads SharedPreferences on the main thread at startup, which shows up as a jank spike in Play’s vitals.

Two Jetpack libraries fix the two halves of this. Paging 3 loads data in pages as the user scrolls, survives configuration changes and can combine a local database with the network. DataStore replaces SharedPreferences with an asynchronous, transactional store built on Kotlin flows. Both are simple to start with and have a few rules that matter a lot in production.

New to some of these? Open what you need, or skip ahead.

Basics:What is a Flow?

A Flow is a stream of values that arrive over time, like the results of a database query that update whenever the data changes. You collect it to receive the values. In Compose, collectAsStateWithLifecycle() collects a flow while the screen is visible. See the Coroutines and Flow lesson.

Basics:What is pagination?

Pagination means loading a long list in pieces, or pages: the first 20 orders, then the next 20 when the user scrolls near the end. The app uses less memory and shows something quickly. The server tells the app how to ask for the next page: a page number, an offset, or a cursor. See cursor paginationCursor paginationLoading the next page by saying where the last page ended, such as 'posts older than this one', instead of using a page number or offset.Open in glossary →.

Part Not started

Loading lists page by page

Paging 3 has three pieces:

  1. PagingSourcePagingSource (Paging 3)The Paging 3 class that loads one page of data for a key and tells the library the keys of the previous and next pages.Open in glossary →: knows how to load one page. You get a key (like page 3) and return the items plus the keys for the previous and next pages.
  2. Pager: wraps the source and produces a Flow<PagingData>, a stream of “the list so far”, which grows as more pages load.
  3. The UI: collectAsLazyPagingItems() gives you a list for LazyColumn. When the user scrolls near the end, Paging loads the next page by itself.

Two lines make it work well:

  • cachedIn(viewModelScope) in the ViewModel keeps the loaded pages when the screen rotates. Without it, rotation starts again from page 1.
  • loadState tells you whether the first page is loading, failed, or the end was reached, so you can show a spinner, an error with Retry, or nothing.

PagingSource<Key, Value>.load(params) returns LoadResult.Page(data, prevKey, nextKey), LoadResult.Error or LoadResult.Invalid; getRefreshKey(state) picks the key to reload around the user’s position after invalidation (typically from state.anchorPosition), which is what keeps scroll position when data changes. Pager(PagingConfig(pageSize, prefetchDistance, enablePlaceholders, maxSize)) produces Flow<PagingData>; apply map/filter/insertSeparators and then cachedIn(viewModelScope) last, so transformations aren’t re-run and rotation reuses pages (a PagingData can only be collected once). In Compose, collectAsLazyPagingItems() + items(count, key = lazyPagingItems.itemKey { it.id }) gives stable keys; loadState.refresh, .append and .source/.mediator drive UI. For offline-first lists, make Room the single source of truth: the DAO returns a PagingSource (auto-invalidated on table changes) and a RemoteMediator loads network pages into the database (including a remote-keys table for cursors), so the UI never reads the network directly and works offline.

class OrdersPagingSource(private val api: OrdersApi) : PagingSource<String, Order>() {

    override suspend fun load(params: LoadParams<String>): LoadResult<String, Order> = try {
        val page = api.orders(cursor = params.key, limit = params.loadSize)     // null key = first page
        LoadResult.Page(data = page.items, prevKey = null, nextKey = page.nextCursor)
    } catch (e: IOException) {
        LoadResult.Error(e)
    } catch (e: HttpException) {
        LoadResult.Error(e)
    }

    // After a refresh, start again from the first page (a cursor API can't jump to the middle)
    override fun getRefreshKey(state: PagingState<String, Order>): String? = null
}

@HiltViewModel
class OrdersViewModel @Inject constructor(api: OrdersApi) : ViewModel() {
    val orders: Flow<PagingData<Order>> =
        Pager(PagingConfig(pageSize = 30, prefetchDistance = 10)) { OrdersPagingSource(api) }
            .flow
            .cachedIn(viewModelScope)                                          // survives rotation
}

@Composable
fun OrdersScreen(viewModel: OrdersViewModel = hiltViewModel()) {
    val orders = viewModel.orders.collectAsLazyPagingItems()

    when (val refresh = orders.loadState.refresh) {
        is LoadState.Loading -> FullScreenSpinner()
        is LoadState.Error -> ErrorScreen(refresh.error, onRetry = orders::retry)
        is LoadState.NotLoading -> LazyColumn {
            items(count = orders.itemCount, key = orders.itemKey { it.id }) { index ->
                orders[index]?.let { OrderRow(it) } ?: OrderRowPlaceholder()
            }
            if (orders.loadState.append is LoadState.Loading) item { RowSpinner() }
            if (orders.loadState.append is LoadState.Error) item { RetryRow(onRetry = orders::retry) }
        }
    }
}
  • load asks the API for one page, using the cursor the previous page returned. nextKey = null means “no more pages”.
  • Errors become LoadResult.Error, which the UI sees as LoadState.Error with a Retry button, instead of crashing.
  • cachedIn(viewModelScope) keeps pages in the ViewModel, which survives rotation.
  • itemKey { it.id } gives each row a stable key, so Compose doesn’t confuse rows when pages load.
  • loadState.refresh is about the first load; loadState.append is about loading more at the end.
Spot the bugBack to page one on every rotation

Tap the line with the bug.

@Composable
fun OrdersScreen(api: OrdersApi) {
    val orders = remember {
        Pager(PagingConfig(pageSize = 30)) { OrdersPagingSource(api) }.flow
    }.collectAsLazyPagingItems()

    LazyColumn {
        items(orders.itemCount) { index -> orders[index]?.let { OrderRow(it) } }
    }
}

Offline-first with RemoteMediator

@OptIn(ExperimentalPagingApi::class)
class OrdersMediator(
    private val api: OrdersApi,
    private val db: ShopDatabase,
) : RemoteMediator<Int, OrderEntity>() {

    override suspend fun load(loadType: LoadType, state: PagingState<Int, OrderEntity>): MediatorResult {
        val cursor = when (loadType) {
            LoadType.REFRESH -> null
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            LoadType.APPEND -> db.remoteKeys().get("orders")?.nextCursor
                ?: return MediatorResult.Success(endOfPaginationReached = true)
        }
        return try {
            val page = api.orders(cursor = cursor, limit = state.config.pageSize)
            db.withTransaction {                                   // one transaction: no empty flash
                if (loadType == LoadType.REFRESH) {
                    db.orders().clearAll()
                    db.remoteKeys().clear("orders")
                }
                db.remoteKeys().put(RemoteKey("orders", page.nextCursor))
                db.orders().insertAll(page.items.map { it.toEntity() })
            }
            MediatorResult.Success(endOfPaginationReached = page.nextCursor == null)
        } catch (e: IOException) {
            MediatorResult.Error(e)                               // cached rows stay visible
        }
    }
}

val orders = Pager(
    config = PagingConfig(pageSize = 30),
    remoteMediator = OrdersMediator(api, db),
    pagingSourceFactory = { db.orders().pagingSource() },        // Room is the single source of truth
).flow.cachedIn(viewModelScope)

The UI only ever reads Room’s PagingSource. Network failures leave cached rows on screen with an append error; a pull-to-refresh calls refresh(), which runs the mediator with REFRESH. Override initialize() to return SKIP_INITIAL_REFRESH when the cache is fresh enough, so opening the screen doesn’t always hit the network.

Predict the output

The orders list shows 120 loaded orders and the user has scrolled to order 90. The PagingSource is invalidated (the user deleted an order). getRefreshKey returns null. Where does the list end up?

  • PagingSource.load → Page(data, prevKey, nextKey) / Error / Invalid; getRefreshKey from anchorPosition preserves scroll after invalidation.
  • Pager(PagingConfig(pageSize, prefetchDistance, maxSize)) → transformations → cachedIn(viewModelScope) last; PagingData is single-collection.
  • Compose: collectAsLazyPagingItems(), itemKey { it.id }, loadState.refresh/append, retry().
  • Offline-first: Room PagingSource as single source of truth + RemoteMediator (remote keys table, REFRESH clear+insert in one transaction, initialize() to skip refreshes).

Check this part

  1. What does cachedIn(viewModelScope) prevent?

  2. What does nextKey = null mean in a LoadResult.Page?

  3. In an offline-first paged list, where does the UI read from?

  4. Why clear and insert in one transaction during REFRESH?

A PagingSource loads one page for a key and returns the next and previous keys. A Pager turns it into a Flow of PagingData; cache it in the ViewModel with cachedIn(viewModelScope) so rotation doesn't reload. In Compose, collectAsLazyPagingItems feeds a LazyColumn with stable item keys, and loadState drives loading, error and retry UI. For offline-first lists, Room is the single source of truth and a RemoteMediator fills it from the network.

Part Not started

Settings and small data with DataStore

SharedPreferences has three problems: its first read happens on whatever thread asks (often the main one), apply() writes later without telling you if it failed, and two quick changes can overwrite each other.

DataStoreDataStoreJetpack's replacement for SharedPreferences: data is read as a Flow and written in atomic, asynchronous transactions.Open in glossary → fixes them:

  • Reading gives you a Flow: the current settings, and new values whenever they change. Collect it in a ViewModel or with collectAsStateWithLifecycle().
  • Writing is a suspend function, edit { }, that runs off the main thread and changes the values atomically: read the old value, compute the new one, save, all as one step.

There are two kinds:

  • Preferences DataStore: key-value pairs, like SharedPreferences. Good for simple settings.
  • Proto DataStore: one typed object (defined with Protocol Buffers or Kotlin serialization). Good when settings have structure.

The most important rule: one DataStore per file in the whole app. Create it once, at the top level or in a singleton, and inject it.

DataStore offers asynchronous, transactional storage with a single-writer model: data: Flow<T> emits the current value and updates; updateData { current -> new } (Preferences: edit { mutablePrefs -> }) runs serialized read-modify-write transactions on an IO dispatcher and surfaces failures as exceptions. Exactly one instance per file per process (multiple instances throw IllegalStateException; use the preferencesDataStore delegate at top level or a Hilt singleton; MultiProcessDataStoreFactory for multi-process access). Never runBlocking { data.first() } on the main thread; if startup needs a value, read it asynchronously or expose a loading state. Handle CorruptionException with a ReplaceFileCorruptionHandler, and IOException in data with catch { emit(emptyPreferences()) }. Migrate with SharedPreferencesMigration, which runs once before the first read. Proto/typed DataStore (with a Serializer using kotlinx.serialization or protobuf) gives a schema and defaults; DataStore is for small data (settings, flags, tokens’ ciphertext), not for lists that belong in Room.

// One instance per file: a top-level delegate on Context
private val Context.settingsStore by preferencesDataStore(
    name = "settings",
    produceMigrations = { context -> listOf(SharedPreferencesMigration(context, "legacy_settings")) },
    corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
)

data class Settings(val darkMode: Boolean, val ordersSeen: Int)

class SettingsRepository @Inject constructor(@ApplicationContext context: Context) {
    private val store = context.settingsStore

    private object Keys {
        val DarkMode = booleanPreferencesKey("dark_mode")
        val OrdersSeen = intPreferencesKey("orders_seen")
    }

    val settings: Flow<Settings> = store.data
        .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
        .map { prefs -> Settings(prefs[Keys.DarkMode] ?: false, prefs[Keys.OrdersSeen] ?: 0) }

    suspend fun setDarkMode(enabled: Boolean) {
        store.edit { it[Keys.DarkMode] = enabled }
    }

    suspend fun markOrderSeen() {
        store.edit { prefs -> prefs[Keys.OrdersSeen] = (prefs[Keys.OrdersSeen] ?: 0) + 1 }   // atomic increment
    }
}
  • by preferencesDataStore(name = "settings") creates the store once for the whole app, the first time it’s used.
  • SharedPreferencesMigration copies the old legacy_settings values into DataStore the first time, so users keep their settings.
  • settings is a Flow<Settings>: collect it and the UI updates when dark mode changes anywhere.
  • edit { } reads and writes in one step, so two quick markOrderSeen() calls give +2, never +1.

Predict the output

Two classes each create their own store: val store = PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("settings") }. Both are used while the app runs. What happens?

Production puzzles

Spot the bugA theme read that costs a frame budget

Tap the line with the bug.

class ShopApp : Application() {
    @Inject lateinit var settings: SettingsRepository

    override fun onCreate() {
        super.onCreate()
        val dark = runBlocking { settings.settings.first().darkMode }
        AppCompatDelegate.setDefaultNightMode(
            if (dark) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO
        )
    }
}

Predict the output

A repository does: suspend fun addFavorite(id: String) { val current = store.data.first()[FAVS] ?: emptySet(); store.edit { it[FAVS] = current + id } }. The user taps "favorite" on two products quickly; both calls run concurrently. What can end up stored?

Exercisehard

Design an offline-first order history

The order history must work offline, show new orders within a minute of opening the screen, let users mark orders as favorites while offline, and handle 40,000 orders per account. Describe the data flow, the paging setup and where favorites live.

›

Decide what the single source of truth is for orders and for favorites, and how each gets to and from the server.

SolutionTry it yourself first
  • Orders: Room is the source of truth. The screen pages through dao.pagingSource(); an OrdersMediator appends older pages by cursor and, on REFRESH, fetches the newest page and upserts it in one transaction (no full clear, so the user’s position and cached history survive). initialize() skips the refresh if the last sync was under a minute ago.
  • Freshness: pull-to-refresh calls refresh(); a periodic WorkManager job can prefetch the first page so the list is current on open.
  • Favorites: a favorite column (or table) in Room, written immediately on tap, plus a pending_sync flag. A WorkManager job with a network constraint pushes pending changes with idempotent requests and clears the flag. The UI reads favorites from Room, so it updates instantly, online or not.
  • Conflicts: server responses don’t overwrite rows with pending_sync; the queue wins until it’s acknowledged.
  • Scale: 40,000 rows is fine in Room with an index on created_at; PagingConfig(pageSize = 50, maxSize = 500) keeps memory bounded while scrolling.
Exercisemedium

Move a setting to DataStore

The app stores “notifications enabled” with prefs.edit().putBoolean("notifications", value).apply() and reads it with prefs.getBoolean("notifications", true) in a ViewModel’s init. Move it to the SettingsRepository above, keep existing users’ values, and expose it to the ViewModel as state.

›

The migration needs the old file’s name; the ViewModel can turn a Flow into a StateFlow with stateIn.

SolutionTry it yourself first
// In SettingsRepository (the store already lists SharedPreferencesMigration for the old file)
private val NotificationsKey = booleanPreferencesKey("notifications")   // same key name as before

val notificationsEnabled: Flow<Boolean> = store.data.map { it[NotificationsKey] ?: true }

suspend fun setNotificationsEnabled(enabled: Boolean) {
    store.edit { it[NotificationsKey] = enabled }
}

// In the ViewModel
val notificationsEnabled: StateFlow<Boolean> = settings.notificationsEnabled
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue = true)

fun onToggle(enabled: Boolean) = viewModelScope.launch { settings.setNotificationsEnabled(enabled) }

SharedPreferencesMigration copies keys from the old file on the first read, so keeping the same key name means existing users keep their choice. The ViewModel no longer reads anything synchronously.

  • data: Flow<T>; edit/updateData are serialized, atomic read-modify-write transactions. Read current values inside the transaction.
  • One instance per file per process (else IllegalStateException); top-level delegate or Hilt singleton; MultiProcessDataStoreFactory across processes.
  • No runBlocking on the main thread; splash setKeepOnScreenCondition or defaults while loading.
  • ReplaceFileCorruptionHandler, catch IOException on data; SharedPreferencesMigration.
  • Preferences for key-value, typed (Proto/serialization) for structured settings; lists belong in Room.

Check this part

  1. How many DataStore instances should exist for one file?

  2. How do you read DataStore values?

  3. Why can reading with data.first() and then calling edit lose updates?

  4. What’s wrong with runBlocking { store.data.first() } in Application.onCreate?

DataStore replaces SharedPreferences: reads are a Flow, writes are suspend functions that update atomically, and errors surface as exceptions. Preferences DataStore stores key-value pairs; Proto DataStore stores a typed object. Create exactly one instance per file (a top-level delegate or a singleton), never block the main thread on it, read-modify-write inside updateData or edit, handle corruption, and migrate from SharedPreferences with SharedPreferencesMigration.

Key takeaways

  • Paging 3 loads lists page by page; create the Pager in a ViewModel with cachedIn.
  • Use loadState for loading, error and retry UI, and stable item keys.
  • DataStore replaces SharedPreferences: read with a Flow, write with edit.
  • One DataStore per file, created once and shared.
  • getRefreshKey and stable keys keep the user’s place across invalidations.
  • Offline-first lists: Room as the source of truth, a RemoteMediator with transactional refreshes.
  • DataStore transactions only protect reads done inside them.
  • Never block the main thread on storage; design startup around asynchronous reads.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.