[Android] Clean your API calls!

Tram Ho

In fact as you work with creating a new API Call. The problem with dealing with server errors and API errors is often the same and repeats each time you create. Repeated processing of a task can lead to errors, boilerplate …

To solve this problem, today we will together clean API calls and recreate the model to receive data from the server returned.

In this article I will clean the Retrofit API call. A library most widely used in Android when handling requests to the server. Also use generic to rewrite the model that received data from the returned server.

A typical API Call often:

Each API call Retrofit when called will return us a Callback<T> object. T here is the generic type is the object containing the data that we receive when the request is completed.

As you can see in the code above Callback<T> is an interface that will be passed into each API Call

Now, instead of using the original Callback provided by Retrofit, we will rewrite by inheriting it, refactor into the same callback we want.

So, if we need a request now, we will use SimpleCallback<T> instead of Callback<T>

Recently we have rewritten Callback<T> . Now we will continue to rewrite the model for our received data.

Normally when the respone returned from the server the error object will be the same, and the data object returned will vary depending on each request. Recognizing this we will use the generic type to rewrite the model.

Status: common to all respones

Respone class will receive data depending on each request so we will use the generic type here:

After combining both SimpleCallback<T> and Respone<T> , our request will now become as follows:

So just now I showed how to clean API Retrofit in Android:

  1. re-implement Callback<T>
  2. Rewrite the model to receive data.

Happy coding!

The article is available at: https://android.jlelse.eu/clean-your-api-calls-79d67098d258

Share the news now

Source : Viblo