RXAndroid + Retrofit.

AkhilBV
MindOrks
Published in
5 min readOct 27, 2018

I am not gonna explain or detail about RxAndroid since there are tons of tutorials and posts about it. I will write on how to use it in our regular day-to-day tasks and how to implement it in our projects or wherever you need it.And you should use because It makes developer lives more easy and most importantly Reactive.

Well this is how you will feel after you code with Rxandroid😜

What is Rx Java:-
At its core, RxJava simplifies development because it raises the level of abstraction around threading. That is, as a developer you don’t have to worry too much about the details of how to perform operations that should occur on different threads. This is particularly attractive since threading is challenging to get right and, if not correctly implemented, can cause some of the most difficult bugs to debug and fix.

It’s made even easier with RxAndroid, a library that wraps asynchronous UI events to be more RxJava like.Well In normal terms its android way of implementing rx java.

So RxAndroid is more like Android way of implementing Rxjava in Android.

It is pretty powerful and you can do many complex operations with just a few lines of code and it almost feels like a magic.

Today i will not go into all details about rxJava, rxAndroid but i will write about how to implement it with retrofit and make networks calls using rxandroid which is also pretty easy to understand.

Now,To get started you need to have basic understanding about rxandroid and observable types and please feel free to reach out the links i mentioned at the bottom to get more in depth understanding of types of observables.

I will explain one of observable type and how to make a network call with it.
Single:-Single is an obervable which only emits a single value or a error so it has only two methods:-
onSuccess(),onError().

The exact definition is:-
A Single is something like an Observable, but instead of emitting a series of values — anywhere from none at all to an infinite number — it always either emits one value or an error notification.

onSuccess
a Single passes this method the sole item that the Single emits
onError
a Single passes this method the Throwable that caused the Single to be unable to emit an item

A Single will call only one of these methods, and will only call it once. Upon calling either method, the Single terminates and the subscription to it ends.

So as mentioned above once it calls a single method than it terminates and if you think it is quite similar to our normal retrofit call method which has two methods:-
onResponse():-which holds the response.
onFailure():-which holds failure message.

So,In general we can use single but it does not apply to all the cases and we have use other observable types depending out requirement.

Show Me The Code:-

Now to use Rxandroid first we have to import dependancy:-
// RxJava
implementation ‘io.reactivex.rxjava2:rxjava:2.1.13’

// RxAndroid
implementation ‘io.reactivex.rxjava2:rxandroid:2.0.2’

And for retrofit:-
// standard retrofit dependency
implementation ‘com.squareup.retrofit2:retrofit:2.3.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.3.0’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.4.1’
implementation ‘com.squareup.retrofit2:converter-scalars:2.1.0’

//you need this to use RxAndroid with retrofit.
implementation ‘com.squareup.retrofit2:adapter-rxjava2:2.4.0’

then while building retrofit:-
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

So after adding the above Retrofit builder should look like this:-

Retrofit rxTutorialRetrofit = new Retrofit.Builder()
.baseUrl(Test_Url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient.build())
.build();

It is a a pet project of mine so don’t bother with it.Just observe the line :-

addCallAdapterFactory(RxJavaCallAdapterFactory.create()).

Be sure to add it while building retrofit because if you don’t then app will crash while making network calls using rxandroid.

Next go to our interface:-


@GET(“users”)
Single<Response<List<SampleUserDetailsPojo>>> getUserDetails();

If you ignore the @GET and all similar code to old way of declaring a call method here we have Mentioned return type as Single instead of Call
and it returns a observable of type single which can be subscribed from activity or fragment.
And ignore my getUserDetails() since it is my sample code and i have used sample api which i found online.

Now to coming to rxjava or rxandroid the most basic concept is we can subscribe to a observable.So from our activity or fragment wherever we need,We can observe to that observable which we declared in our interface.

In Activity(you can use it in fragment too just like you use a retrofit api call.)
Use below code to make call.

Single<Response<List<SampleUserDetailsPojo>>> testObservable= TestApplication.getRestClient().getRestInterface().getUserDetails();testObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Response<List<SampleUserDetailsPojo>>>() {
@Override
public void onSubscribe(Disposable d) {
}@Override
public void onSuccess(Response<List<SampleUserDetailsPojo>> listResponse) {
}@Override
public void onError(Throwable e) {
}
});

So,Now i will explain what each line.

subscribeOn(Schedulers.io())

Threading in Rxandroid is done with the help of schedulers.To be more precise schedulers are like a ThreadPool managing one or more Threads.So, If a schedulers need to perform a task then it will take a Thread from pool and will run that task on it.

Subscribeon() specifies on which Scheduler the work will be done.In our case it is to make a network and Schedulers.io() is backed by unbounded ThreadPool. It can be used for non CPU-intensive I/O type like network calls and database calls etc.And if you want you can dig more about it and you really should.

So, The result will be received on the same Thread that runs the task and since we need the data on UI Thread, We need to use oberveOn.

.observeOn(AndroidSchedulers.mainThread())

Here with observeOn we have to mention in what thread do we need our results and And as you can see i gave AndroidSchedulers.mainThread() and the result will be fetched back to main thread so we can update ui according to the response.

To sum up what it does is it will make api call in background thread and provides us response in Main-thread(UI Thread).

Pretty convenient and easy right.So,Without Rxandorid if we have do the above operation than we have use a Asyntask and interface…sshhhh I will not go over there!!! It is pretty heavy and complicated task.And we can do that in just two lines of code using rxandroid. And that is what i call Magic.

So getting back,Next i have subscribed to the observable and as you can see It has override two methods OnSuccess() and OnError();
in OnSuccess() we will receive our response which in my case is a list and i can update my adapter with list or whatever UI related action i have to perform. And in onError we will receive a Throwable and we can handle with the error with it and way we want to.

And next n onSubscribe() we receive a disposable and we have to dispose it because if we don’t there will be memory leaks which will kill our app slowly.What onSubscribe gives us is a disposable object of our subscription.

So,This is it and you are good to go and your Networks Call now should look more Reactive.As i said it is pretty powerful and Awesome.

if you find it useful just give me a clap 👏👏👏 and do feel free to comment and share.

Happy Coding.

Some Usefull Links:-

Types of Observables in RxJava

https://proandroiddev.com/understanding-rxjava-subscribeon-and-observeon-744b0c6a41ea

Refer two links above and i really liked the way they explained about it.

--

--

MindOrks
MindOrks

Published in MindOrks

Our community publishes stories worth reading on Android Development

AkhilBV
AkhilBV

Written by AkhilBV

Enthusiastic Self taught Android Developer.

Responses (2)