Created
May 21, 2022 04:00
-
-
Save MamboBryan/2d38bbec1f42cb430bd9332cee6ea992 to your computer and use it in GitHub Desktop.
The paging source
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
package com.mambobryan.samba.data.remote | |
import androidx.paging.PagingSource | |
import androidx.paging.PagingState | |
import com.mambobryan.samba.data.model.Character | |
import com.mambobryan.samba.utils.Constants | |
import kotlinx.coroutines.delay | |
import retrofit2.HttpException | |
import timber.log.Timber | |
import java.io.IOException | |
class CharactersPagingSource( | |
private val apiService: ApiService, | |
) : PagingSource<Int, Character>() { | |
override fun getRefreshKey(state: PagingState<Int, Character>): Int? { | |
return state.anchorPosition?.let { anchorPosition -> | |
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) | |
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) | |
} | |
} | |
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Character> { | |
val page = params.key ?: Constants.START_PAGE | |
return try { | |
val response = apiService.getCharacters(page) | |
val articles = response.characters | |
val nextKey = if(response.info?.next.isNullOrBlank()) null else page + 1 | |
// val nextKey = if (articles.isEmpty()) null else page + 1 | |
val previousKey = if (page == Constants.START_PAGE) null else page - 1 | |
delay(3000) | |
LoadResult.Page(data = articles, prevKey = previousKey, nextKey = nextKey) | |
} catch (exception: IOException) { | |
return LoadResult.Error(exception) | |
} 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