Hi guys, I am using pagination library for fetch the data from the API call, and got to know that my...
k

KV

over 4 years ago
Hi guys, I am using pagination library for fetch the data from the API call, and got to know that my API calls are made 3 times, with page number: 1 , 2 , 3 With Page Number 1 -> I got success response - which is correct behaviour. But does anyone know why page number 2 and 3 triggers (which is failure)?
private const val STARTING_PAGE_INDEX = 1

class AbsencePagingDataSource(
    private val apiProvider: ApiProvider,
    private val absenceDataMapper: AbsenceDataMapper,
    private val workspaceId: String
) :
    PagingSource<Int, AbsenceData>() {
    lateinit var response: ListApiResponse<WorkspaceAbsenceResponse>

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AbsenceData> {
        val position = params.key ?: STARTING_PAGE_INDEX

        val request = Endpoint.GetWorkspaceAbsence(
            workspaceId = workspaceId,
            Queries = listOf(
                Queries.Paginate(position, 50),   -------> SEE URL BELOW
            )
        )
        return try {
            apiProvider.api.performRequest<ListApiResponse<WorkspaceAbsenceResponse>>(request).map { listApiResponse ->
                response = listApiResponse
            }
            val endOfPaginationReached = response.data.isEmpty()

            LoadResult.Page(
                data = absenceDataMapper.mapToDomain(response),
                prevKey = if (position == STARTING_PAGE_INDEX) null else position - 1,
                nextKey = if (endOfPaginationReached) null else position + 1
            )
        } catch (exception: IOException) {
            LoadResult.Error(exception)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, AbsenceData>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }
}

URL/request looks like -> 
---------------------------
1. url=<https://PATH/api/v3/workspaces/120/absences?page=1&items=50> ----> 200
2. url=<https://PATH/api/v3/workspaces/120/absences?page=2&items=50> ----> 422
3. url=<https://PATH/api/v3/workspaces/120/absences?page=3&items=50> ----> 422