Retrofit

Retrofit is a type-safe REST client for Android and Java by Square. It helps you easily communicate with any REST API. It integrates perfectly with RxJava: all the JSON response objects are mapped to plain old Java objects and all the network calls are based on RxJava Observable of these objects.

Using the API documentation, we can define what JSON response we will receive from the server. To easily map this JSON response to our Java code, we will use jsonschema2pojo (http://www.jsonschema2pojo.org). This handy service will generate all the Java classes we need to map the JSON response.

When we have all the Java models in place, we can start setting up Retrofit. Retrofit uses standard Java interfaces to map the API routes. For our example, we are going to use just a route from the API, and our Retrofit interface class will be the following:

public interface StackExchangeService {
    @GET("/2.2/users?order=desc&sort=reputation&site=stackoverflow")Observable<UsersResponse> getMostPopularSOusers(@Query("pagesize") int howmany);
}

This interface class contains only one method, for now: getMostPopularSOusers. This method takes integer howmany as a parameter and returns an Observable of UsersResponse.

When we have interface, we can create the RestAdapter class. We obviously want to organize our code properly, and we will create a SeApiManager function to provide a proper way to interact with the StackExchange API:

public class SeApiManager {

    private final StackExchangeService mStackExchangeService;

    public SeApiManager() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("https://api.stackexchange.com")
                .setLogLevel(RestAdapter.LogLevel.BASIC)
                .build();

        mStackExchangeService = restAdapter.create(StackExchangeService.class);
    }

    public Observable<List<User>> getMostPopularSOusers(int  howmany) {
        return mStackExchangeService
              .getMostPopularSOusers(howmany)
                .map(UsersResponse::getUsers)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}

For the simplicity of the example, we will not manage this class as it should be managed: Singleton. Using a dependency injection solution, such as Dagger2, would bring the code quality even higher.

Creating the RestAdapter class, we will set up a few important aspects of our API client. In this example, we are setting the endpoint and the log level. The endpoint URL is hardcoded only for the sake of the example. It's important to use an external resource to store data like this. Avoiding hardcoded strings in the code is a good practice.

The Retrofit setup ends binding our RestAdapter class and our API Interface. This will give us an object that we can use to query the API. We can choose to directly expose this object, or wrap it somehow, to limit access to it. In this example, we are wrapping it and exposing only getMostPopularSOusers. This method executes the query, lets Retrofit parse the JSON response, extracts the list of users, and provides it back to the subscriber. As you can see, using Retrofit, RxJava, and Retrolambda, we have almost no boilerplate code: it's very compact and the readability is very high.

Now, we have an API manager that exposes a reactive method, which fetches data from a remote API to an I/O Scheduler, parses it, maps it, and provides a neat users list for our consumers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75