REST and ReactiveX in Android

Introduction

Our first priority in developing software in Rococo Global Technologies Corporation (RGTC) is to make high quality software. To achieve this, we use tools and libraries that will help us to make readable, maintainable, and high-quality software. Two of the libraries that we use in our Android applications is RxJava and Retrofit.

Retrofit supports both blocking and non-blocking HTTP calls. This is sufficient most of the time, but for those who are looking to have more control over when to start and stop HTTP calls, RxJava is the perfect fit. Using RxJava allows us to fine-tune app transitions by stopping HTTP calls when we don’t care about its response anymore and by automatically freeing up resources held by such HTTP requests.

Including Retrofit and ReactiveX to your project

Retrofit

When you use retrofit, you also need to include another library which is a converter you will use with Retrofit. If your server will return JSON, you can either use Jackson, Gson, etc. There are also converters for XML.

compile 'com.squareup.retrofit2:retrofit:2.1.0'

To include RxJava in your project, add the following lines to your app’s build.gradle file.

compile 'io.reactivex:rxjava:1.2.0'
compile 'io.reactivex:rxandroid:1.2.1'

The second line is a supporting library for Android’s use. When you’re dealing with network operations in Android, it is a standard practice to do it in a separate thread. In fact, Android will throw an exception if you attempt to do network operations on the main thread.

Example Usage

If your app depends mostly on the server side, it is a good idea to initialize your Retrofit’s instance early on. We usually define our interface like this.

public interface GithubService {

    String BASE_URL = "https://api.github.com/";

    @GET("users/{username}/repos")
    Observable<List<Repository>> getRepositories(@Path("username") String username);

    GithubService INSTANCE = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(BASE_URL)
            .build()
            .create(GithubService.class);

}

By using this interface, we can call our API like this:

GithubService.INSTANCE.getRepositories("torvalds")
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(repositories -> {
            Log.i(TAG, repositories.toString());
        }, exception -> {
            Log.e(TAG, "onError", exception);
        });

This will return a list of repositories of a user who has a username “torvalds” on Github. Note that we’re using lambdas here. Lambdas were made available since Java 8. Android does not support Java 8 features natively, but there’s a neat gradle plugin we can use so that we can use Lambdas throughout our code base. You can also choose not to use the plugin, but I suggest that you use it. It makes your code a lot cleaner and much more readable.

To use it, open your project’s build.gradle file and add classpath 'me.tatarka.gradle-retrolambda:3.3.0' under the `dependencies` object and add mavenCentral() under `repositories` which is under `allprojects`. Then on your app’s build.gradle file, add apply plugin: 'me.tatarka.retrolambda' on the 2nd line and add the following under `android`.

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Conclusion

In conclusion, there are going to be a lot of ways in solving problems but mobile apps require much more attention when it comes to dealing with resources effectively and efficiently because of hardware constraints. There is a reason why Retrofit and RxJava is so popular right now. So, it’s your choice to use it or not. Have fun!

Leave a Reply

Your email address will not be published.