Android RxJava and Retrofit With Examples

In this tutorial, we’ll be implementing Retrofit calls using RxJava in android app. We’ll be creating an application that populates a RecyclerView using Retrofit and RxJava. We’ll be using a CryptoCurrency API.

What Will You Learn?

  • Making a Retrofit call using RxJava.
  • Doing Multiple Retrofit Calls Using RxJava
  • Transforming the Retrofit POJO response using RxJava

We’ll be using Java 8 in our Android Application to unleash lambda expressions.

Overview

Retrofit is a REST client that uses OkHttp as the HttpClient and JSON Parsers to parse the response.
We’ll use gson as the JSON Parser here.
This is how a Retrofit instance is created:

HttpLoggingInterceptor is used to log the data during the network call.

RxJava is a library that is used for asynchronous and reactive programming in the form of streams.
We use different threads in RxJava. A background thread for the network call and the main thread for updating the UI.
Schedulers in RxJava is responsible for performing operations using different threads.
RxAndroid is an extension of RxJava and it contains the Android threads to be used in the Android Environment.

To use RxJava in retrofit environment we need to do just two major changes:

  • Add the RxJava in Retrofit Builder.
  • Use Observable type in the interface instead of Call

To do multiple calls or transform the response, we use RxJava operators.
Let’s see how it’s done through our sample application below.

Project Structure

android-rxjava-retrofit-project-structure

Add the following dependencies in our build.gradle file:

Code

The code for the layout activity_main.xml is given below.

The code for the CryptocurrencyService.java class is given below.

@Path passes in the path we specify into the curly braces.
Note: The @Path parameter name must match with the one in the @GET.

The POJO class Crypto.java is given below:

coinName is a field we’ve set. Using the magic of RxJava we’ll set a value on this field to transform the response.

Creating a Single Call Using RxJava

subscribeOn() creates a Scheduler thread over which we do the network call.
We can pass any of the following Schedulers in it.

  • trampoline(): This runs the tasks on the current thread. So it’ll run your code after the current task on the thread is complete. Useful for queueing operations.
  • newThread(): Creates and returns a Scheduler that creates a new Thread for each unit of work. This is costly since it creates a separate thread everytime.
  • computation(): Creates and returns a Scheduler intended for computational work. This should be used for parallel work since the thread pool is bound. I/O operations shouldn’t be done here.
  • io(): Creates and returns a Scheduler intended for IO-bound work. Again it’s bounded like computation. Typically this is used for network calls.

subscribeOn() vs observeOn()

  • subscribeOn works downstream and upstream. All the tasks above and below it would use the same thread.
  • observeOn works downstream only.
  • consecutive subscribeOn methods won’t change the thread. Only the first subscribeOn thread would be used.
  • consecutive observeOn methods will change the thread.
  • After an observeOn(), putting a subscribeOn() won’t change the thread. Hence observeOn should generally come after a subscribeOn.

AndroidSchedulers.mainThread() is a part of RxAndroid and is used to observe the data on the main thread only.

subscribe method is what triggers the retrofit call and gets the data in the method handleResults which we’ll see shortly.

Multiple Calls

We use the RxJava operator merge to do two retrofit calls one after the other.

Transforming the Response

To transform the POJO response we can do the following:

We use Observable.fromIterable to convert the the map result into Observable streams.
flatMap works on the elements one by one. Thus converting the ArrayList to single singular elements.
In the filter method we change the response.
toList() is used to convert the results of flatMap back into a List.
toObservable() wraps them as Observable streams.

MainActivity.java

The code for the MainActivity.java class is given below:

handleResults and handleError are invoked using the Java 8 invocation ::
In the handlResults we set the converted response on the ReyclerViewAdapter.
handleError() is invoked if the response has an error.

The code for the recyclerview_item_layout layout is given below.

The code for the RecyclerViewAdapter.java class is given below:

The output of the above application in action is given below:
android-rxjava-retrofit-output

The above output merges the results of the Bitcoin and Ethereum market prices done through retrofit.

This brings an end to this tutorial. You can download the Android RxJavaRetrofit Project from the link below.

By admin

Leave a Reply

%d bloggers like this: