Skip to content

Pagination

2.0.0 · Feature · Data Module

Interacting with paginated API will need a lot of work, codebase use Jetpack Paging.

Defining ApiClient

Make ApiClient as usual, because it's paginated API so there will be page in int (for example) as parameter.

UserApiClient.kt
interface UserApiClient {
    @GET("users")
    fun getUserPerPage(@Query("page") page: String): 
        Single<Response<DevApiResponse<List<UserItem>>>>
}

Defining DataStore

For the DataStore class, we will be calling toPagingData() method to convert our ApiClient as Paging Data Source.

UserDataStore.kt
class UserDataStore(web: UserApi) : UserRepository {

    override val webService = web

    override fun getUsersPerPage(): Flowable<PagingData<UserItem>> =
        toPagingData(6) { page ->
            webService.getUserPerPage(page.toString())
                    .lift(singleApiError())
                    .map { it.data }
        }
}

the toPagingData() method took int parameter that will be defining how many of data will be displayed for each page.

And as you can see, the page parameter will be defined by the lambda. So there's no need for passing page parameter from presentation layer. Notice the highlighted line, return your method with Flowable<PagingData<>> to contain your object data.


Passing another parameter

There's time where the API took more than just page as parameter, so what you want to do is define your your ApiClient like this:

UserApiClient.kt
interface UserApiClient {
    @GET("users")
    fun getUserPerPage(@Query("page") page: String, @Query("type") type : String): 
        Single<Response<DevApiResponse<List<UserItem>>>>
}

Then define your DataStore like this:

UserDataStore.kt
class UserDataStore(web: UserApi) : UserRepository {

    override val webService = web

    override fun getUsersPerPage(type : String): Flowable<PagingData<UserItem>> =
        toPagingData(6) { page ->
            webService.getUserPerPage(page.toString(), type)
                .lift(singleApiError())
                .map { it.data }
        }
}

By providing the addition parameter (outside of the page number) from presentation layer.

See also: Pagination in Presentation layer