In this blog, we will focus on handling API calls using Retrofit and RxJava. In order to help you understand better, I have divided it into three parts. First, we’ll look into Retrofit, then we move to RxJava, and then lastly, we’ll see how it is done with Retrofit and RxJava combined.

Let us take a detailed look into the each of them.

Retrofit

Retrofit is an awesome library from Square. It is a type-safe REST client for android, which is designed to easily retrieve and upload JSON – or, any other structured data – through a REST based web service.

Here is the step-by-step process to use Retrofit.

  1. Add the following dependencies in your build.grade file.

  1. Create Retrofit Builder Class

You need to create Retrofit Builder class and specify the base URL for the service to make a network request to the API.

  1. Define the Endpoints

Now, you need to define the endpoints inside the interface using annotations to encode details about the parameters and request methods. Please make sure the return value is always represented inside Call i.e., Call<Model Class> object.

Below, the annotation of HTTP method can either be GET, POST, PUT etc. And method parameters may be @Query, @Path, @Body etc.

  1. Requesting the API from an activity

We will make a request from our activity onCreate() method as follows:

Retrofit will get and parse the response on a background thread, and then will return the results back to the UI thread via the onResponse, or onFailure method.

RxJava

RxJava is a library for enabling Reactive Programming in Android. You can create asynchronous data stream on any thread, transform the data, and consume it by an Observer on any thread.

RxAndroid: RxAndroid is specific to Android platform, which is similar to RxJava with added classes on top of RxJava. Especially schedulers are available in RxAndroid, which plays a major role in supporting multithreading concept in android application. Schedulers will decide on which thread the code should run, i.e. whether on background thread or main thread.

For example:

Schedulers.newThread() – this will create a new thread.

AndroidSchedulers.mainThread() – this provides access to android Main Thread/UI Thread.

RxJava components are Observable, observer, schedulers, operators and subscription.

Observable – it’s a source of data or events in reactive programming, which emits the data.

Observer – it’s a counterpart of observable, which receives the data emitted by observable.

Subscription – the bonding between Observable and Observer is called as Subscription. There can be multiple Observers subscribed to a single Observable.

Operator – are functions that defines the observable on how and when it should emit the data stream.

Schedulers – being one of main components in RxJava, they are responsible for performing operations of Observable on different threads.

So, Observable emits the data stream while Observers (also known as Subscribers) receive them. There can be any number of observers. See below image.

Creating the Observable that emits data.

Creating an observer that listen to observable

onSubscribe(): Method gets called when an Observer subscribes to Observable.

onNext(): Method gets called when Observable starts emitting the data.

onError(): Method gets called when errors occur.

onComplete(): Method gets called when an Observable completes the emission of all the items.

subscribeOn(Schedulers.io()): Which makes Observable to run the task on a background thread.

observeOn(AndroidSchedulers.mainThread()): Which makes Observer to receive the data on android UI thread so that you can take any UI related actions.

Disposable

Basically we use disposable to avoid memory leaks. Memory leaks can be avoided by disposing the subscription of the observer to the observable when observer no longer wants to listen to observable.

Filters

They are used to filter the data emitted by the observable by using conditional statement.

Retrofit and RxJava

Now, lets combine Retrofit with RxJava.

Creating Retrofit Builder Class

First, you need to create Retrofit Builder class and specify the base URL for the service to make a network request to the API.

Creating an interface

The below interface holds the methods of every endpoint by defining the endpoint, request and response Observable.

Using ApiClient and ApiService you can make a network call.

Conclusion

Retrofit and RxJava, without a doubt, are one of the best libraries out there. We hope the above process helped you in learning how to handle API calls using Retrofit and RxJava.

                                                                        **

Ideaplunge is one of the leading tech solutions companies around. We offer intuitive and user-centric Android and iOS solutions to startups and Enterprises. Our solutions have helped transform businesses, and add value to end-users.

Got a Android project on your mind? Write to us at talktous@idealunge.com

Leave a Reply

Your email address will not be published. Required fields are marked *