/
UsersPagingSource.kt
33 lines (28 loc) · 1.1 KB
/
UsersPagingSource.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.theozgurr.composesamplepaginationapp
import androidx.paging.PagingSource
import androidx.paging.PagingState
class UsersPagingSource(
private val repository: UserRemoteRepository
) : PagingSource<Int, UserDto>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserDto> =
try {
val perPage = params.key ?: PAGE_SIZE
val since = perPage - PAGE_SIZE
val users = repository.getUsers(since = since, perPage = perPage)
LoadResult.Page(
data = users,
prevKey = null,
nextKey = if (users.isEmpty()) null else perPage + PAGE_SIZE
)
} catch (e: Exception) {
LoadResult.Error(e)
}
override fun getRefreshKey(state: PagingState<Int, UserDto>): Int? =
state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(PAGE_SIZE) ?: anchorPage?.nextKey?.minus(PAGE_SIZE)
}
companion object {
const val PAGE_SIZE = 20
}
}