Yokan / rebuild
Course 1 8624561

15-paging3.md

.codex/skills/compose-kotlin-agent-skills/references/15-paging3.md

documentation / design asset258 lines
1---2name: paging33description: >4  Paging 3 with Compose — PagingSource, RemoteMediator, LazyPagingItems, LoadState UI,5  2026 asState() presenter pattern, append/prepend triggers. Use when building paginated lists.6version: "2.2.0"7updated: "2026-05-21"8---910# Paging 3 — Compose, RemoteMediator, 2026 Presenter APIs1112## Pinned versions (2026)1314```toml15paging = "3.3.6"16```1718```kotlin19implementation("androidx.paging:paging-runtime:3.3.6")20implementation("androidx.paging:paging-compose:3.3.6")21```2223---2425## WRONG / RIGHT 1 — PagingSource blocking network on main2627```kotlin28// WRONG — blocking call inside load()29class BadPagingSource(private val api: Api) : PagingSource<Int, Item>() {30    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {31        val page = params.key ?: 032        val response = api.fetchSync(page)  // blocking retrofit call33        return LoadResult.Page(response.items, prevKey = page - 1, nextKey = page + 1)34    }35    override fun getRefreshKey(state: PagingState<Int, Item>): Int? =36        state.anchorPosition?.let { state.closestPageToPosition(it)?.prevKey?.plus(1) }37}3839// RIGHT — suspend API, map errors to LoadResult.Error40class ItemPagingSource(41    private val api: Api,42    private val query: String43) : PagingSource<Int, ItemDto>() {44    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ItemDto> = try {45        val page = params.key ?: 046        val response = api.search(query, page, params.loadSize)47        LoadResult.Page(48            data = response.items,49            prevKey = if (page == 0) null else page - 1,50            nextKey = if (response.items.isEmpty()) null else page + 151        )52    } catch (e: Exception) {53        LoadResult.Error(e)54    }5556    override fun getRefreshKey(state: PagingState<Int, ItemDto>): Int? =57        state.anchorPosition?.let { anchor ->58            state.closestPageToPosition(anchor)?.let { page ->59                page.prevKey?.plus(1) ?: page.nextKey?.minus(1)60            }61        }62}63```6465---6667## WRONG / RIGHT 2 — collectAsLazyPagingItems() in ViewModel (deprecated pattern)6869```kotlin70// WRONG — Compose collector belongs in UI layer, not ViewModel71@HiltViewModel72class BadListViewModel @Inject constructor(repo: ItemRepository) : ViewModel() {73    val lazyItems = repo.pager.flow.collectAsLazyPagingItems()  // Compose API in VM74}7576// RIGHT (2026) — expose PagingData Flow; presenter collects as State in UI77@HiltViewModel78class ItemListViewModel @Inject constructor(79    private val repository: ItemRepository80) : ViewModel() {81    private val _query = MutableStateFlow("")82    val query: StateFlow<String> = _query.asStateFlow()8384    val pagingFlow: Flow<PagingData<ItemUi>> = _query85        .flatMapLatest { repository.pagerFor(it).flow }86        .map { pagingData -> pagingData.map { dto -> dto.toUi() } }87        .cachedIn(viewModelScope)8889    fun onQueryChanged(value: String) {90        _query.update { value }91    }92}93```9495---9697## WRONG / RIGHT 3 — 2026 presenter: pager.flow.asState() + collectAsStateWithLifecycle9899```kotlin100// WRONG — old collectAsLazyPagingItems only in Composable without initial snapshot101@Composable102fun ItemListScreen(vm: ItemListViewModel = hiltViewModel()) {103    val lazyItems = vm.pagingFlow.collectAsLazyPagingItems()104    // no placeholder during first load — flicker105}106107// RIGHT (2026) — asState() in presenter layer with initialList for stable first frame108@Composable109fun ItemListScreen(vm: ItemListViewModel = hiltViewModel()) {110    val pagingState by vm.pagingFlow111        .asState(initialList = emptyList())  // paging-compose 2026 extension112        .collectAsStateWithLifecycle()113114    ItemListContent(115        items = pagingState.items,116        loadState = pagingState.loadState,117        onRetry = { vm.retry() }118    )119}120```121122> **Note:** `Flow<PagingData<T>>.asState(initialList)` caches the latest `LazyPagingItems`-equivalent snapshot for lifecycle-aware collection. Check `androidx.paging:paging-compose` release notes for your BOM pin.123124---125126## WRONG / RIGHT 4 — Ignoring LoadState in Compose UI127128```kotlin129// WRONG — crash on empty/error; no retry130@Composable131fun ItemList(lazyItems: LazyPagingItems<ItemUi>) {132    LazyColumn {133        items(lazyItems.itemCount) { index ->134            Text(lazyItems[index]!!.title)135        }136    }137}138139// RIGHT — handle refresh/append LoadState + placeholders140@Composable141fun ItemListContent(142    items: List<ItemUi?>,143    loadState: CombinedLoadStates,144    onRetry: () -> Unit145) {146    LazyColumn {147        if (loadState.refresh is LoadState.Loading && items.isEmpty()) {148            item(key = "loading") { CircularProgressIndicator(Modifier.fillMaxWidth()) }149        }150        items(151            count = items.size,152            key = { index -> items[index]?.id ?: "placeholder-$index" },153            contentType = { "item" }154        ) { index ->155            val item = items[index]156            if (item != null) {157                ItemRow(item)158            } else {159                ItemPlaceholder()160            }161        }162        if (loadState.append is LoadState.Loading) {163            item(key = "append_loading") { LinearProgressIndicator(Modifier.fillMaxWidth()) }164        }165        if (loadState.refresh is LoadState.Error) {166            item(key = "error") {167                ErrorRow(message = stringResource(R.string.error_load), onRetry = onRetry)168            }169        }170    }171}172```173174---175176## WRONG / RIGHT 5 — Manual append/prepend triggers (2026 Pager API)177178```kotlin179// WRONG — hack refresh by recreating entire Pager on every scroll edge180fun loadMore() {181    pager = Pager(config) { ItemPagingSource(api, query) }  // new instance, lost scroll182}183184// RIGHT — Pager.append / Pager.prepend for explicit load triggers185@HiltViewModel186class ItemListViewModel @Inject constructor(187    private val repository: ItemRepository188) : ViewModel() {189    private var pager: Pager<Int, ItemDto>? = null190191    fun bindPager(query: String): Flow<PagingData<ItemUi>> {192        val p = repository.buildPager(query).also { pager = it }193        return p.flow.map { data -> data.map { it.toUi() } }.cachedIn(viewModelScope)194    }195196    fun appendNextPage() {197        viewModelScope.launch {198            pager?.append()  // paging-runtime 2026 — triggers append LoadType199        }200    }201202    fun prependPreviousPage() {203        viewModelScope.launch {204            pager?.prepend()205        }206    }207}208```209210---211212## RemoteMediator — offline-first213214```kotlin215@OptIn(ExperimentalPagingApi::class)216class ItemRemoteMediator(217    private val db: AppDatabase,218    private val api: Api219) : RemoteMediator<Int, ItemEntity>() {220    override suspend fun load(221        loadType: LoadType,222        state: PagingState<Int, ItemEntity>223    ): MediatorResult {224        return try {225            val page = when (loadType) {226                LoadType.REFRESH -> 0227                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)228                LoadType.APPEND -> {229                    val last = db.itemDao().lastRemoteKey()230                        ?: return MediatorResult.Success(endOfPaginationReached = true)231                    last + 1232                }233            }234            val response = api.fetch(page)235            db.withTransaction {236                if (loadType == LoadType.REFRESH) {237                    db.itemDao().clearAll()238                }239                db.itemDao().insertAll(response.items.map { it.toEntity() })240            }241            MediatorResult.Success(endOfPaginationReached = response.items.isEmpty())242        } catch (e: Exception) {243            MediatorResult.Error(e)244        }245    }246}247```248249## Decision matrix250251| Scenario | Pattern |252|---|---|253| Network-only list | `PagingSource` |254| Room + network sync | `RemoteMediator` + Room DAO `PagingSource` |255| Search query changes | `flatMapLatest` on query → new `Pager` |256| UI collection | `asState(initialList)` + `collectAsStateWithLifecycle` |257| User taps "Load more" | `pager.append()` |258| Pull-to-refresh | `LazyPagingItems.refresh()` or new refresh trigger |259

Search chapters, reference and source filenames.