Skip to content

Instantly share code, notes, and snippets.

@DivS-15
Created May 17, 2022 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DivS-15/5aed81945d67b99ec373214becd4a6fc to your computer and use it in GitHub Desktop.
Save DivS-15/5aed81945d67b99ec373214becd4a6fc to your computer and use it in GitHub Desktop.
private const val STARTING_PAGE_TOKEN = " "
class VideosPagingSource @Inject constructor(
private val coroutineScope: CoroutineScope,
private val remoteApiService: VideosRemoteInterface
) : PagingSource<String, Item>() {
override fun getRefreshKey(state: PagingState<String, Item>): String? {
var current: String? = " "
val anchorPosition = state.anchorPosition
coroutineScope.launch {
if (anchorPosition != null) {
current = state.closestPageToPosition(anchorPosition)?.prevKey?.let {
remoteApiService.getMostPopularVideos(
it
).nextPageToken
}
}
}
return current
}
override suspend fun load(params: LoadParams<String>): LoadResult<String, Item> {
val start = params.key ?: STARTING_PAGE_TOKEN
return try {
val response = remoteApiService.getMostPopularVideos(start)
val nextKey = if (response.items.isEmpty()) null else response.nextPageToken
val prevKey = if (start == STARTING_PAGE_TOKEN) null else response.prevPageToken
LoadResult.Page(
data = response.items,
prevKey = prevKey,
nextKey = nextKey
)
}catch (e: IOException){
return LoadResult.Error(e)
}catch (exception: HttpException){
return LoadResult.Error(exception)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment