Skip to content

Commit

Permalink
[feat] #7 paging source
Browse files Browse the repository at this point in the history
  • Loading branch information
Sangwook123 committed May 3, 2024
1 parent a4f86ee commit 4e97682
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/data/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@ dependencies {
implementation(projects.core.datastore)
implementation(projects.core.database)
implementation(projects.core.common)
implementation(projects.core.network)
implementation(libs.retrofit.kotlin.serialization)
implementation(libs.kotlinx.serialization.json)
implementation(libs.androidx.paging)
}
39 changes: 39 additions & 0 deletions core/data/src/main/java/org/sopt/data/paging/UserPagingSource.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package org.sopt.data.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import org.sopt.model.ReqresUser
import org.sopt.network.api.ReqresApi
import org.sopt.network.model.response.toReqresUser
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject

class UserPagingSource @Inject constructor(
private val reqresApi: ReqresApi,
) : PagingSource<Int, ReqresUser>() {
override fun getRefreshKey(state: PagingState<Int, ReqresUser>): Int? {
return state.anchorPosition
}

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ReqresUser> {
return try {
val currentPage = params.key ?: 1
val users = toReqresUser(
reqresApi.getUsers(
currentPage
).data
)

LoadResult.Page(
data = users,
prevKey = if (currentPage == 1) null else currentPage - 1,
nextKey = if (users.isEmpty()) null else currentPage + 1
)
} catch (exception: IOException) {
return LoadResult.Error(exception)
} catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}

0 comments on commit 4e97682

Please sign in to comment.