Retrofit pagination

How paging works in Retrofit

For a more complete and in-depth explanation, check out our complete Retrofit course

Download the starter project here

Github repository

Retrofit doesn’t natively support paging, and the reason for that is paging is not a function of communicating back and forth with the API, it’s more a function of implementation. Paging is done through implementation and not through Retrofit.

It depends on how the server manages paging that you would be able to implement it in code. That is part of the reason why it’s not natively supported by Retrofit.

How to implement

The way you implement paging in an application is simply you perform multiple requests with a certain changed parameter. So for instance if your API requires your query parameter to indicate the page, then you do that. Otherwise it’s done in whatever way it’s required by the API.

Examples

So here are a few examples that you might encounter in the real world

example.com/users?page=1

@GET(“users”)

fun getUsers(@Query(“page”) page: Int): Call<List<Users>>

If your API requires the page parameter in a query. In this case you would have a function that takes a page parameter and uses the @Query annotation to pass it to the request.

This needs to be implemented in code rather than in Retrofit.

Let’s take another example.

example.com/users/page/get

@GET(“users/{page}/get”)

fun getUsers(@Path(“page”) page: Int): Call<List<Users>>

In this example, the API requires the page to be specified as a path component in your URL.

In that case you would build your function using the @Path parameter so that the page number is passed to the URL and it replaces the “page” part of your URL.

If you want to see a realistic example of how this is implemented, have a look at my course as it contains a complete project that deals with paging in a real world application.

Complete Retrofit for Android development course

We will build an app that contacts the StackOverflow API, retrieves a list of questions that are paged, as well as a list of answers to each question that are also retrieved page by page.

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner
Bitnami