
Offline-first pagination for page/limit APIs using a local SQL cache, windowed loading with placeholders, transactional window refreshes, global updateItem propagation, and UI-agnostic trackers.
Offline-first pagination for Kotlin Multiplatform. For page / limit APIs, with a local SQLDelight cache and no UI dependency: use it with Compose, SwiftUI, UIKit or Android Views.
totalCount long, unloaded positions are null placeholders.updateItem, changes an item in every list that shows it.Runs in production Android and iOS apps and is proven by thousands of users.
Targets: Android, iOS (iosArm64, iosSimulatorArm64), JVM / Desktop.
One tour of the demo app on KPage, Android on the left and iOS on the right. Both clips are recorded from the demo's tour tests, which drive the real app through the system like a person (UiAutomator on Android, XCUITest on iOS), so nothing in them is staged. More about every screen is in the demo README.
|
Android |
iOS |
The images come from NASA live, so the pictures differ from run to run. The long runs along the list, the typing and the waits between steps are sped up (the Android clip up to 3×, the iOS clip up to 4×); the rest plays at its own pace. The steps are the same on both platforms.
See it working:
demo/is a complete Android + iOS app on this library (NASA image search, favorites, a chat with a mock server, settings) with shared logic and fully native UI. Jump to the demo.
On this page: Install · Quick start · API at a glance · Guide · Demo
| Problem | What KPage does |
|---|---|
| A long list should not be loaded or kept whole | Keeps a window of pages around the visible position in memory and in the database; the rest is deleted |
| The server shifts items while the user scrolls | Items are addressed by server position (page * pageSize + index), so a shifted page leaves no holes |
| A refresh must not break the screen | Reloads the whole window, replaces it in one transaction, keeps the old data on screen until then; on failure nothing changes |
| One item is shown in several lists (a tab, a search, a favorites list) | Items are stored once per type; updateItem reaches every list, open ones too |
| Offline start | Cached list and totalCount are shown before the first request |
| Different UI toolkits | The library draws nothing; any UI reports its visible rows through a small tracker |
KPage is built for APIs where any page can be requested by its number, and everything above relies on that. Cursor-based APIs ("give me the items after X") are a different model and out of scope.
kotlin {
sourceSets {
commonMain.dependencies {
implementation("io.github.wladyslawpopov:paging-core:2.1.0")
}
}
}Built with Kotlin 2.4 and SQLDelight 2.4. The library has no Compose dependency; kotlinx.serialization and the SQLDelight coroutine extensions come with it (their types are part of the API).
If your iOS app links the Kotlin framework statically, add -lsqlite3 to the linker flags.
One PagingDatabase for the whole app, shared by all paginators. Create it in platform code:
// Android
val db = PagingDatabase(createPagingDriver(context))
// iOS: stored in Caches, not backed up to iCloud
val db = PagingDatabase(createPagingDriver())
// JVM / Desktop: the app chooses the directory
val db = PagingDatabase(createPagingDriver(File(System.getProperty("user.home"), ".myapp")))For tests and previews use createInMemoryPagingDriver() (on Android it takes a Context). The cache is disposable: when a new version changes the schema, the library opens a new file and deletes the old ones. Nothing is migrated.
Items are stored as JSON, so the type must be @Serializable. getPage returns a PagerPayload:
@Serializable
data class User(val id: String, val name: String, val isLiked: Boolean = false)
suspend fun getUsers(page: Int, pageSize: Int): PagerPayload<User> {
val response = api.users(page = page, limit = pageSize)
return PagerPayload(
totalCount = response.total, // or null if the API does not report it
isMore = response.hasNext,
objects = response.items,
)
}getPage receives page + initialPageKey: set initialPageKey = 1 if your pages start at 1.
Create it where the list is owned (a ViewModel, a component, a presenter) and pass that owner's scope:
class UsersHolder(api: UsersApi, db: PagingDatabase, scope: CoroutineScope) {
private val config = PaginatorConfig(pageSize = 30)
val paginator: Paginator<User> = StablePaginator(
serializer = User.serializer(),
queryKey = "users", // the name of this list in the cache, never sent to the server
config = config,
getPage = { page -> api.getUsers(page, config.pageSize) },
idExtractor = { it.id },
db = db,
scope = scope,
)
val state: StateFlow<PagingState<User>> = paginator.state
}paginator.state has everything the UI needs, read from one database snapshot:
items: PagedList<T>: size == totalCount, null is a placeholder;totalCount: restored from the cache on a cold start;loadState: see Loading state;isRestored: false until the cache has been read, so an empty list before that means "not read yet".The paginator loads its first window by itself and refreshes it once when it is created. After that the refresh is yours: you call refresh() at the moments your business logic needs it (see Refresh).
The UI does two things: draws items, and tells the paginator which rows are on screen with a PagingListTracker. In Compose that is a short helper:
@Composable
fun TrackVisibleRows(state: LazyListState, rows: PagingRowSource, events: PagingEvents) {
val currentRows by rememberUpdatedState(rows)
val tracker = remember(events) { PagingListTracker(events) }
LaunchedEffect(state, tracker) {
snapshotFlow { VisibleRows(currentRows, state.layoutInfo.visibleItemsInfo.map { it.index }) }
.collect { tracker.onLayout(it.rows, it.indexes) }
}
}
// Not a data class: snapshotFlow would compare the rows with equals on every change.
private class VisibleRows(val rows: PagingRowSource, val indexes: List<Int>)@Composable
fun UsersScreen(holder: UsersHolder) {
val state by holder.state.collectAsState()
val listState = rememberLazyListState()
val rows = remember(state.items) { state.items.rows() }
val keys = remember(rows) { rows.keys { it.id } }
TrackVisibleRows(listState, rows, holder.paginator)
LazyColumn(state = listState) {
items(count = rows.rowCount, key = keys) { index ->
state.items[index]?.let { UserRow(it) } ?: UserRowPlaceholder()
}
}
}Two rules:
decorate, not with a separate item { }, or the positions shift.rows.keys { it.id } keeps the id and adds the position only to a repeated one, so rows stay stable when new items shift the list.SwiftUI and UIKit use the same tracker: the demo's PagedGrid.swift is a complete example, see UI without Compose.
| Task | Call | Notes |
|---|---|---|
| Show the list | paginator.state |
items, totalCount, loadState, isRestored
|
| Report what is on screen | PagingListTracker(events).onLayout(rows, visibleRows) |
on every layout change |
| Refresh | refresh() |
where the user is: pull-to-refresh, retry, after removing items on the server; returns when it is over |
| Refresh from the top | scroll to the top, then refresh()
|
the window follows the scroll |
| Jump to a position | scroll the list | the window follows by itself |
| Read the full item | getItemById(id) |
when rows hold a display model |
| Change one item | updateItem(id) { it.copy(...) } |
after the server confirmed; every list sees it |
| Change an item without a paginator | db.updateItem(serializer, id) { ... } |
for example from a details screen |
| Remove items | server call, then refresh()
|
no local shifting |
| Headers, separators, local rows | state.items.decorate { ... } |
returns PagingRows
|
| Manage the cache |
db.clearCache(), db.setMaxLists(n), db.cacheStats()
|
|
| Stop | cancel the owner's scope |
close() only to replace a paginator earlier |
Every chapter starts with what you need; the details are folded.
The paginator keeps the visible pages plus prefetchDistance pages on each side loaded (default 1: about 3 pages on a phone). When the user scrolls to another page, only the missing pages are requested and loads outside the window are cancelled. Besides the window, extraPagesInDb (2) nearest pages stay in the database for scrolling back; farther pages are deleted.
scope.launch {
paginator.refresh() // returns when the refresh is over
}One refresh, and it works where the user is: it requests the pages of the current window again, ignoring the cache, and replaces them in one transaction. The old data stays on screen meanwhile (loadState = REFRESH).
One rule for the whole API: state tells what is going on with the list, and the calls of the app (refresh(), updateItem(), getItemById()) suspend until they are done. A pull-to-refresh indicator simply stays until refresh() returns.
totalCount and drops the pages outside the window (they are stale and load again when the user scrolls there).loadState = ERROR, and a retry button can call refresh() as often as needed.refresh() returns when the new data is written, when it failed (the error is in state, not thrown), or when a scroll out of the window or close() ended it. It never waits forever.refresh() again restarts it. A refresh asked while another runs replaces it, and both calls return when the new one is over.refresh() is yours: call it on a pull, on a retry, on a signal of your business logic (a cleared cache, a changed favorite) or when the screen comes back, one line wherever your app needs it. Nothing renews behind your back, so counters and positions stay exactly as the user sees them until you decide. A changed query is a new paginator with a new queryKey.refresh() as well.getPage must only read: pages of one refresh are loaded in parallel and the length is taken from the last page, so a side effect inside getPage makes the total disagree with the list.| State | When | What to show |
|---|---|---|
INITIAL |
loading with nothing to show (no cache) | a full-screen loader |
REFRESH |
refreshing over the shown cache | a subtle indicator, or nothing |
NEXT |
pages of the window loading while scrolling | placeholders |
IDLE |
the window is loaded, more data after it | nothing |
END |
the window is loaded and reaches the end |
totalCount == 0 means "nothing found" |
ERROR(error) |
the last load failed; the cache is intact | an error with a retry that calls refresh()
|
when (val load = state.loadState) {
LoadState.INITIAL -> FullScreenLoader()
is LoadState.ERROR -> ErrorBanner(load.error.message, onRetry = paginator::refresh)
else -> Unit
}Pass totalCount = null. The list is then as long as its loaded part, with no placeholders after it; the next page is requested when the user nears the end; the end is a page with isMore = false or fewer items than pageSize (loadState = END). The loading indicator at the bottom is yours, for example a footer.
fun onLikeClick(id: String) = scope.launch {
api.addToFavourites(id) // the server first
paginator.updateItem(id) { it.copy(isLiked = true) } // then the cache
}Items are stored once per type and shared by all lists, so the change appears at every position in every list. updateItem returns the new item, or null if it is not cached.
Removing is a server operation, often over a selection that is not even in the cache, so there is no removeItem: delete on the server, then refresh().
transform gets the current cached version; reading and writing happen in one step. updateItem(id) { newItem } replaces the whole item. An exception thrown by transform goes to the caller. JSON in the cache that cannot be read gives null and is kept.refresh() if the screen needs the new one at once. The same holds for PagingDatabase.updateItem, which has no paginator of its own.getItemById(id) reads the full item from the cache, for example when rows hold only a display model and a server call or a details screen needs the whole item. Keep no copies of items of your own.Without extra rows use items.rows(). For extra rows use decorate. Every decoration is placed before a server position (0..items.size); only loaded items and decorations are visited, so the cost does not depend on totalCount:
val rows = remember(state.items, promos, drafts) {
state.items.decorate<Post, FeedDecor> {
if (promos.isNotEmpty()) header(FeedDecor.Banner(promos)) // before position 0
between { prev, next -> // both neighbours loaded
if (prev.day != next.day) FeedDecor.Date(next.day) else null
}
drafts.forEach { insert(beforeIndex = 0, FeedDecor.Local(it)) } // anchored rows
footer(FeedDecor.End) // after the last position
}
}
val keys = remember(rows) { rows.keys { it.id } }
LazyColumn(state = listState) {
items(count = rows.rowCount, key = keys) { i ->
when (val row = rows[i]) {
is PagingRow.Item -> row.item?.let { PostRow(it) } ?: PostPlaceholder()
is PagingRow.Decoration -> DecorRow(row.value)
}
}
}decorate returns PagingRows, not a List: use rows.rowCount and rows[i]. It is not a list on purpose: Kotlin/Native turns every List into an NSArray, so SwiftUI would get a converted copy. PagingRows crosses by reference and is read row by row.between is called only for neighbours that are both loaded.decorationKey to keys to key it by your own identity. A placeholder is keyed slot:N.keys once per rows (remember(rows) { ... }): it walks the loaded items.items.loadedIndices, not the whole list.PagingIndexedItem (server rows return their server index, decorative rows null) and be passed through PagingRowSource.of(list) when you do not use decorate.The tracker needs one call, onLayout(rows, visibleRows), from wherever the UI learns what is on screen. In SwiftUI the demo uses onScrollTargetVisibilityChange, in a few lines:
tracker = events.map { PagingListTracker(events: $0) } // a new paginator gets a new tracker
tracker.onLayout(rows: list.rows, visibleRows: visible.map { KotlinInt(int: Int32($0)) })events object (the paginator itself): a new paginator gets a new one. Call it from the main thread.PagingRows.keys, made once per snapshot as on Android: SwiftUI reads the identity of every row on each update, and the keys keep the scroll position when a row is added or removed.PagedGrid.swift (SwiftUI) and TrackVisibleRows.kt (Compose).The paginator lives exactly as long as its scope. Cancel the owner's scope and loads, the database subscription and event handling stop; there is nothing to call. close() stops one paginator earlier than its owner, typically when it is replaced after a filter change.
queryKey alive twice) is fine: every extra live paginator keeps its pages separately, so the screens do not delete each other's data.dispatcher (Dispatchers.Default) runs events, JSON decoding and getPage calls; do not pass Main. Only the job of scope is used, so a Main scope is fine.databaseDispatcher (platform default) runs database work. Paginators of one database should share it; the cache functions below take the same one.StandardTestDispatcher for both dispatchers and backgroundScope as the scope: advanceUntilIdle() then runs everything deterministically.db.clearCache() // everything, for example on logout
db.clearCache("users") // one list
db.setMaxLists(50) // stored in the database; the oldest lists beyond it are evicted
db.maxLists() // 100 by default
db.cacheStats() // PagingCacheStats(lists, items, dataBytes), for a settings screendataBytes is the size of the stored items; it drops right after a cleanup, unlike the database file, which SQLite does not shrink.clearCache() after the lists are closed, for example on logout, so nothing of the previous user stays. Under a live list it empties the list and leaves it empty until the app calls refresh(): the library does not refresh by itself, or the data of the previous user would come back into the cache. The demo shows a way: the repository announces the clear as a flow, and the screens with lists subscribe and call refresh().PaginatorConfig(
pageSize = 60, // items per page
prefetchDistance = 1, // pages loaded on each side of the visible ones
initialPageKey = 0, // number of the first page in your API (0 or 1)
extraPagesInDb = 2, // spare pages kept beyond the window
)Invalid values throw at creation.
pagedListOf(size, loaded) builds a PagedList without a paginator or a database: size positions, of which loaded (position to item) are filled and the rest are placeholders. Use it for previews, UI tests and fake paginators:
val items = pagedListOf(size = 100, loaded = mapOf(0 to User("1", "Anna"), 1 to User("2", "Ben")))
val state = PagingState(items, totalCount = 100, loadState = LoadState.IDLE, isRestored = true)PagingState.initial() and PagingRows.empty() are the empty values for a screen state that mirrors a paginator. The library's own tests: ./gradlew :paging-core:jvmTest.
@Serializable type, so it does not overwrite the full one.getPage: the same page number returns the same slice of the list until the data changes; positions are addressed by page * pageSize + index.demo/ is the answer to "what does it look like in a real app": Android (Compose) and iOS (SwiftUI) with one shared Kotlin logic layer (domain, data, presentation) and a fully native UI on each side. It brings together the practices I use in production apps.
What it shows with this library: a 10 000-row NASA search with filters, an offline cache, updateItem in every list at once, a reversed chat list with date separators and local messages, cache management in settings.
Copyright 2026 Vladyslav Popov
Licensed under the Apache License, Version 2.0
See LICENSE.
Offline-first pagination for Kotlin Multiplatform. For page / limit APIs, with a local SQLDelight cache and no UI dependency: use it with Compose, SwiftUI, UIKit or Android Views.
totalCount long, unloaded positions are null placeholders.updateItem, changes an item in every list that shows it.Runs in production Android and iOS apps and is proven by thousands of users.
Targets: Android, iOS (iosArm64, iosSimulatorArm64), JVM / Desktop.
One tour of the demo app on KPage, Android on the left and iOS on the right. Both clips are recorded from the demo's tour tests, which drive the real app through the system like a person (UiAutomator on Android, XCUITest on iOS), so nothing in them is staged. More about every screen is in the demo README.
|
Android |
iOS |
The images come from NASA live, so the pictures differ from run to run. The long runs along the list, the typing and the waits between steps are sped up (the Android clip up to 3×, the iOS clip up to 4×); the rest plays at its own pace. The steps are the same on both platforms.
See it working:
demo/is a complete Android + iOS app on this library (NASA image search, favorites, a chat with a mock server, settings) with shared logic and fully native UI. Jump to the demo.
On this page: Install · Quick start · API at a glance · Guide · Demo
| Problem | What KPage does |
|---|---|
| A long list should not be loaded or kept whole | Keeps a window of pages around the visible position in memory and in the database; the rest is deleted |
| The server shifts items while the user scrolls | Items are addressed by server position (page * pageSize + index), so a shifted page leaves no holes |
| A refresh must not break the screen | Reloads the whole window, replaces it in one transaction, keeps the old data on screen until then; on failure nothing changes |
| One item is shown in several lists (a tab, a search, a favorites list) | Items are stored once per type; updateItem reaches every list, open ones too |
| Offline start | Cached list and totalCount are shown before the first request |
| Different UI toolkits | The library draws nothing; any UI reports its visible rows through a small tracker |
KPage is built for APIs where any page can be requested by its number, and everything above relies on that. Cursor-based APIs ("give me the items after X") are a different model and out of scope.
kotlin {
sourceSets {
commonMain.dependencies {
implementation("io.github.wladyslawpopov:paging-core:2.1.0")
}
}
}Built with Kotlin 2.4 and SQLDelight 2.4. The library has no Compose dependency; kotlinx.serialization and the SQLDelight coroutine extensions come with it (their types are part of the API).
If your iOS app links the Kotlin framework statically, add -lsqlite3 to the linker flags.
One PagingDatabase for the whole app, shared by all paginators. Create it in platform code:
// Android
val db = PagingDatabase(createPagingDriver(context))
// iOS: stored in Caches, not backed up to iCloud
val db = PagingDatabase(createPagingDriver())
// JVM / Desktop: the app chooses the directory
val db = PagingDatabase(createPagingDriver(File(System.getProperty("user.home"), ".myapp")))For tests and previews use createInMemoryPagingDriver() (on Android it takes a Context). The cache is disposable: when a new version changes the schema, the library opens a new file and deletes the old ones. Nothing is migrated.
Items are stored as JSON, so the type must be @Serializable. getPage returns a PagerPayload:
@Serializable
data class User(val id: String, val name: String, val isLiked: Boolean = false)
suspend fun getUsers(page: Int, pageSize: Int): PagerPayload<User> {
val response = api.users(page = page, limit = pageSize)
return PagerPayload(
totalCount = response.total, // or null if the API does not report it
isMore = response.hasNext,
objects = response.items,
)
}getPage receives page + initialPageKey: set initialPageKey = 1 if your pages start at 1.
Create it where the list is owned (a ViewModel, a component, a presenter) and pass that owner's scope:
class UsersHolder(api: UsersApi, db: PagingDatabase, scope: CoroutineScope) {
private val config = PaginatorConfig(pageSize = 30)
val paginator: Paginator<User> = StablePaginator(
serializer = User.serializer(),
queryKey = "users", // the name of this list in the cache, never sent to the server
config = config,
getPage = { page -> api.getUsers(page, config.pageSize) },
idExtractor = { it.id },
db = db,
scope = scope,
)
val state: StateFlow<PagingState<User>> = paginator.state
}paginator.state has everything the UI needs, read from one database snapshot:
items: PagedList<T>: size == totalCount, null is a placeholder;totalCount: restored from the cache on a cold start;loadState: see Loading state;isRestored: false until the cache has been read, so an empty list before that means "not read yet".The paginator loads its first window by itself and refreshes it once when it is created. After that the refresh is yours: you call refresh() at the moments your business logic needs it (see Refresh).
The UI does two things: draws items, and tells the paginator which rows are on screen with a PagingListTracker. In Compose that is a short helper:
@Composable
fun TrackVisibleRows(state: LazyListState, rows: PagingRowSource, events: PagingEvents) {
val currentRows by rememberUpdatedState(rows)
val tracker = remember(events) { PagingListTracker(events) }
LaunchedEffect(state, tracker) {
snapshotFlow { VisibleRows(currentRows, state.layoutInfo.visibleItemsInfo.map { it.index }) }
.collect { tracker.onLayout(it.rows, it.indexes) }
}
}
// Not a data class: snapshotFlow would compare the rows with equals on every change.
private class VisibleRows(val rows: PagingRowSource, val indexes: List<Int>)@Composable
fun UsersScreen(holder: UsersHolder) {
val state by holder.state.collectAsState()
val listState = rememberLazyListState()
val rows = remember(state.items) { state.items.rows() }
val keys = remember(rows) { rows.keys { it.id } }
TrackVisibleRows(listState, rows, holder.paginator)
LazyColumn(state = listState) {
items(count = rows.rowCount, key = keys) { index ->
state.items[index]?.let { UserRow(it) } ?: UserRowPlaceholder()
}
}
}Two rules:
decorate, not with a separate item { }, or the positions shift.rows.keys { it.id } keeps the id and adds the position only to a repeated one, so rows stay stable when new items shift the list.SwiftUI and UIKit use the same tracker: the demo's PagedGrid.swift is a complete example, see UI without Compose.
| Task | Call | Notes |
|---|---|---|
| Show the list | paginator.state |
items, totalCount, loadState, isRestored
|
| Report what is on screen | PagingListTracker(events).onLayout(rows, visibleRows) |
on every layout change |
| Refresh | refresh() |
where the user is: pull-to-refresh, retry, after removing items on the server; returns when it is over |
| Refresh from the top | scroll to the top, then refresh()
|
the window follows the scroll |
| Jump to a position | scroll the list | the window follows by itself |
| Read the full item | getItemById(id) |
when rows hold a display model |
| Change one item | updateItem(id) { it.copy(...) } |
after the server confirmed; every list sees it |
| Change an item without a paginator | db.updateItem(serializer, id) { ... } |
for example from a details screen |
| Remove items | server call, then refresh()
|
no local shifting |
| Headers, separators, local rows | state.items.decorate { ... } |
returns PagingRows
|
| Manage the cache |
db.clearCache(), db.setMaxLists(n), db.cacheStats()
|
|
| Stop | cancel the owner's scope |
close() only to replace a paginator earlier |
Every chapter starts with what you need; the details are folded.
The paginator keeps the visible pages plus prefetchDistance pages on each side loaded (default 1: about 3 pages on a phone). When the user scrolls to another page, only the missing pages are requested and loads outside the window are cancelled. Besides the window, extraPagesInDb (2) nearest pages stay in the database for scrolling back; farther pages are deleted.
scope.launch {
paginator.refresh() // returns when the refresh is over
}One refresh, and it works where the user is: it requests the pages of the current window again, ignoring the cache, and replaces them in one transaction. The old data stays on screen meanwhile (loadState = REFRESH).
One rule for the whole API: state tells what is going on with the list, and the calls of the app (refresh(), updateItem(), getItemById()) suspend until they are done. A pull-to-refresh indicator simply stays until refresh() returns.
totalCount and drops the pages outside the window (they are stale and load again when the user scrolls there).loadState = ERROR, and a retry button can call refresh() as often as needed.refresh() returns when the new data is written, when it failed (the error is in state, not thrown), or when a scroll out of the window or close() ended it. It never waits forever.refresh() again restarts it. A refresh asked while another runs replaces it, and both calls return when the new one is over.refresh() is yours: call it on a pull, on a retry, on a signal of your business logic (a cleared cache, a changed favorite) or when the screen comes back, one line wherever your app needs it. Nothing renews behind your back, so counters and positions stay exactly as the user sees them until you decide. A changed query is a new paginator with a new queryKey.refresh() as well.getPage must only read: pages of one refresh are loaded in parallel and the length is taken from the last page, so a side effect inside getPage makes the total disagree with the list.| State | When | What to show |
|---|---|---|
INITIAL |
loading with nothing to show (no cache) | a full-screen loader |
REFRESH |
refreshing over the shown cache | a subtle indicator, or nothing |
NEXT |
pages of the window loading while scrolling | placeholders |
IDLE |
the window is loaded, more data after it | nothing |
END |
the window is loaded and reaches the end |
totalCount == 0 means "nothing found" |
ERROR(error) |
the last load failed; the cache is intact | an error with a retry that calls refresh()
|
when (val load = state.loadState) {
LoadState.INITIAL -> FullScreenLoader()
is LoadState.ERROR -> ErrorBanner(load.error.message, onRetry = paginator::refresh)
else -> Unit
}Pass totalCount = null. The list is then as long as its loaded part, with no placeholders after it; the next page is requested when the user nears the end; the end is a page with isMore = false or fewer items than pageSize (loadState = END). The loading indicator at the bottom is yours, for example a footer.
fun onLikeClick(id: String) = scope.launch {
api.addToFavourites(id) // the server first
paginator.updateItem(id) { it.copy(isLiked = true) } // then the cache
}Items are stored once per type and shared by all lists, so the change appears at every position in every list. updateItem returns the new item, or null if it is not cached.
Removing is a server operation, often over a selection that is not even in the cache, so there is no removeItem: delete on the server, then refresh().
transform gets the current cached version; reading and writing happen in one step. updateItem(id) { newItem } replaces the whole item. An exception thrown by transform goes to the caller. JSON in the cache that cannot be read gives null and is kept.refresh() if the screen needs the new one at once. The same holds for PagingDatabase.updateItem, which has no paginator of its own.getItemById(id) reads the full item from the cache, for example when rows hold only a display model and a server call or a details screen needs the whole item. Keep no copies of items of your own.Without extra rows use items.rows(). For extra rows use decorate. Every decoration is placed before a server position (0..items.size); only loaded items and decorations are visited, so the cost does not depend on totalCount:
val rows = remember(state.items, promos, drafts) {
state.items.decorate<Post, FeedDecor> {
if (promos.isNotEmpty()) header(FeedDecor.Banner(promos)) // before position 0
between { prev, next -> // both neighbours loaded
if (prev.day != next.day) FeedDecor.Date(next.day) else null
}
drafts.forEach { insert(beforeIndex = 0, FeedDecor.Local(it)) } // anchored rows
footer(FeedDecor.End) // after the last position
}
}
val keys = remember(rows) { rows.keys { it.id } }
LazyColumn(state = listState) {
items(count = rows.rowCount, key = keys) { i ->
when (val row = rows[i]) {
is PagingRow.Item -> row.item?.let { PostRow(it) } ?: PostPlaceholder()
is PagingRow.Decoration -> DecorRow(row.value)
}
}
}decorate returns PagingRows, not a List: use rows.rowCount and rows[i]. It is not a list on purpose: Kotlin/Native turns every List into an NSArray, so SwiftUI would get a converted copy. PagingRows crosses by reference and is read row by row.between is called only for neighbours that are both loaded.decorationKey to keys to key it by your own identity. A placeholder is keyed slot:N.keys once per rows (remember(rows) { ... }): it walks the loaded items.items.loadedIndices, not the whole list.PagingIndexedItem (server rows return their server index, decorative rows null) and be passed through PagingRowSource.of(list) when you do not use decorate.The tracker needs one call, onLayout(rows, visibleRows), from wherever the UI learns what is on screen. In SwiftUI the demo uses onScrollTargetVisibilityChange, in a few lines:
tracker = events.map { PagingListTracker(events: $0) } // a new paginator gets a new tracker
tracker.onLayout(rows: list.rows, visibleRows: visible.map { KotlinInt(int: Int32($0)) })events object (the paginator itself): a new paginator gets a new one. Call it from the main thread.PagingRows.keys, made once per snapshot as on Android: SwiftUI reads the identity of every row on each update, and the keys keep the scroll position when a row is added or removed.PagedGrid.swift (SwiftUI) and TrackVisibleRows.kt (Compose).The paginator lives exactly as long as its scope. Cancel the owner's scope and loads, the database subscription and event handling stop; there is nothing to call. close() stops one paginator earlier than its owner, typically when it is replaced after a filter change.
queryKey alive twice) is fine: every extra live paginator keeps its pages separately, so the screens do not delete each other's data.dispatcher (Dispatchers.Default) runs events, JSON decoding and getPage calls; do not pass Main. Only the job of scope is used, so a Main scope is fine.databaseDispatcher (platform default) runs database work. Paginators of one database should share it; the cache functions below take the same one.StandardTestDispatcher for both dispatchers and backgroundScope as the scope: advanceUntilIdle() then runs everything deterministically.db.clearCache() // everything, for example on logout
db.clearCache("users") // one list
db.setMaxLists(50) // stored in the database; the oldest lists beyond it are evicted
db.maxLists() // 100 by default
db.cacheStats() // PagingCacheStats(lists, items, dataBytes), for a settings screendataBytes is the size of the stored items; it drops right after a cleanup, unlike the database file, which SQLite does not shrink.clearCache() after the lists are closed, for example on logout, so nothing of the previous user stays. Under a live list it empties the list and leaves it empty until the app calls refresh(): the library does not refresh by itself, or the data of the previous user would come back into the cache. The demo shows a way: the repository announces the clear as a flow, and the screens with lists subscribe and call refresh().PaginatorConfig(
pageSize = 60, // items per page
prefetchDistance = 1, // pages loaded on each side of the visible ones
initialPageKey = 0, // number of the first page in your API (0 or 1)
extraPagesInDb = 2, // spare pages kept beyond the window
)Invalid values throw at creation.
pagedListOf(size, loaded) builds a PagedList without a paginator or a database: size positions, of which loaded (position to item) are filled and the rest are placeholders. Use it for previews, UI tests and fake paginators:
val items = pagedListOf(size = 100, loaded = mapOf(0 to User("1", "Anna"), 1 to User("2", "Ben")))
val state = PagingState(items, totalCount = 100, loadState = LoadState.IDLE, isRestored = true)PagingState.initial() and PagingRows.empty() are the empty values for a screen state that mirrors a paginator. The library's own tests: ./gradlew :paging-core:jvmTest.
@Serializable type, so it does not overwrite the full one.getPage: the same page number returns the same slice of the list until the data changes; positions are addressed by page * pageSize + index.demo/ is the answer to "what does it look like in a real app": Android (Compose) and iOS (SwiftUI) with one shared Kotlin logic layer (domain, data, presentation) and a fully native UI on each side. It brings together the practices I use in production apps.
What it shows with this library: a 10 000-row NASA search with filters, an offline cache, updateItem in every list at once, a reversed chat list with date separators and local messages, cache management in settings.
Copyright 2026 Vladyslav Popov
Licensed under the Apache License, Version 2.0
See LICENSE.