Run Jetpack Compose Paging on Background/IO Thread

December 14, 2021

Based on Jetpack Compose Paging Sample

class MemberSource(private val repo: MemberRepository) : PagingSource<Int, Member>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Member> {
        val page = params.key ?: 1

        return try {
            withContext(Dispatchers.IO) {
                return LoadResult.Page(
                    data = repo.getMembers(page),
                    prevKey = if (page == 1) null else page - 1,
                    nextKey = if (page * repo.pageSize < repo.totalCount) page + 1 else null
                )
            }
        }
        catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Member>): Int? {
        return state.anchorPosition
    }

}

or

class MemberRepository(val pageSize: Int) {
    suspend fun getMembers(page: Int): List<Gallery.LocalImage> {
        return withContext(Dispatchers.IO) {
            // call coroutines to return result

            val random = Random(page)

            val startIndex = (page - 1) * pageSize + 1
            var endIndex = startIndex + pageSize - 1
            if (endIndex > totalCount) {
                endIndex = totalCount
            }

            delay(3000)

            return  (startIndex..endIndex).map { index ->
                Member(name = "Member #${index}", age = random.nextInt(1, 99))
            }
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.