generated from NOW-SOPT-ANDROID/now-sopt-android-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a4f86ee
commit 4e97682
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
core/data/src/main/java/org/sopt/data/paging/UserPagingSource.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |