Run Jetpack Compose Paging on Background/IO Thread

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))            }        }    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.