OiO.lk Blog Android Why is the Paging3 PagingState not saving items?
Android

Why is the Paging3 PagingState not saving items?


I’m doing a pokedex example app in compose but the pagination works only if i close and reopen the application.

override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, PokemonEntity>
    ): MediatorResult {

        val page = when(loadType) {
            LoadType.REFRESH -> 0
            LoadType.PREPEND -> return MediatorResult.Success(
                endOfPaginationReached = true
            )
            LoadType.APPEND -> {
                val lastItem = state.lastItemOrNull()
                if (lastItem == null) {
                    return MediatorResult.Success(endOfPaginationReached = true)
                } else {
                    lastItem.id / state.config.pageSize
                }
            }
        }

        return try {

            val pokemonList = pokemonApi.getPokemonList(
                limit = state.config.pageSize,
                offset = page * state.config.pageSize
            )
            val endOfPaginationReached = pokemonList.results.isEmpty()

            pokemonDb.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    pokemonDb.dao.clearAll()
                }
                val pokemonEntities = pokemonList.results.map { it.toPokemonEntity() }
                pokemonDb.dao.upsertAll(pokemonEntities)
            }

            return MediatorResult.Success(
                endOfPaginationReached = endOfPaginationReached
            )

        } catch (e: Exception) {
            MediatorResult.Error(e)
        }
    }
@OptIn(ExperimentalPagingApi::class)
@Provides
@Singleton
fun providePokemonPager(pokemonApi: PokemonApi, pokemonDatabase: PokemonDatabase): Pager<Int, PokemonEntity> {
    return Pager(
        config = PagingConfig(pageSize = PokemonApi.PAGE_SIZE),
        remoteMediator = PokemonRemoteMediator(
            pokemonDb = pokemonDatabase,
            pokemonApi = pokemonApi
        ),
        pagingSourceFactory = { pokemonDatabase.dao.pagingSource() }
    )
}

Although the caching with room is working, state: PagingState doesn’t keep the items, so the function state.lastItemOrNull() always returns null. But if i reopen the application works correctly.

Any suggestions? Tysm

I already tried to invalidate the pagingSource, but I really don’t know what to do



You need to sign in to view this answers

Exit mobile version