Skip to content

Commit

Permalink
[chore] #7 paging source
Browse files Browse the repository at this point in the history
  • Loading branch information
Sangwook123 committed May 10, 2024
1 parent 6f84b9c commit 86ceaf6
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions core/data/src/main/java/org/sopt/data/paging/UserPagingSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ class UserPagingSource @Inject constructor(
private val reqresApi: ReqresApi,
) : PagingSource<Int, ReqresUser>() {
override fun getRefreshKey(state: PagingState<Int, ReqresUser>): Int? {
return state.anchorPosition
return state.anchorPosition?.let {
state.closestPageToPosition(it)?.prevKey?.plus(1)
?: state.closestPageToPosition(it)?.nextKey?.minus(1)
}
}

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ReqresUser> {
return try {
val currentPage = params.key ?: 1
val currentPage = params.key ?: INITIAL_KEY
val users = toReqresUser(
reqresApi.getUsers(
currentPage
Expand All @@ -27,7 +30,7 @@ class UserPagingSource @Inject constructor(

LoadResult.Page(
data = users,
prevKey = if (currentPage == 1) null else currentPage - 1,
prevKey = if (currentPage == INITIAL_KEY) null else currentPage - 1,
nextKey = if (users.isEmpty()) null else currentPage + 1
)
} catch (exception: IOException) {
Expand All @@ -36,4 +39,8 @@ class UserPagingSource @Inject constructor(
return LoadResult.Error(exception)
}
}

companion object {
private const val INITIAL_KEY = 1
}
}

0 comments on commit 86ceaf6

Please sign in to comment.