Learning RxJava 2 for Android – Basics Guide

So RxJava is the new thing every android developer wants to get their hands on, but when it comes to learning, it feels hard. Initially, it may feel hard but you might feel super-powered when you get it. I was trying to learn it a few days back and found myself, trying to figure out what actually RxJava is? I went through a lot of articles and videos and want to summarise everything I know about RxJava.

What is RxJava? Why do we need it?

RxJava is Java VM implementation of Reactive Programming. Reactive programming is a practice of programming with asynchronous data streams or event streams. So RxJava is a library for composing asynchronous or event-based programs. Managing threads is a huge problem and using multiple Async Tasks creates problem. If they are not managed properly, may lead to memory leaks. So RxJava comes here to rescue, solves the problem of managing threads.

Before we move further, I want to recommend you to watch this video.

Getting Started.

RxAndroid is an extension to RxJava. It is recommended to implement both RxJava and RxAndroid in your gradle. So Add the two lines below to you app gradle, and make sure you replace 2.x.x with latest version of RxJava.

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.x.x' 
// where 2.x.x should be replaced with latest version

Building Blocks of RxJava.

There are two building blocks, Observables and Subscribers. The observables are the ones that emits items and subscribers are the one that consume these items. An observable may emit any number of items (even zero). Observables don’t emit items, until some subscriber subscribes. Observables emit items and then they terminate either with successful completion or due to error.

RXJava Hello World Example.

Here’s how to create an observable.

Observable<String> observable = Observable.just("Hello World!");
observable.subscribe(s -> System.out.println(s));

So the above example will print the output:

Hello World!

RXJava work as this: The subscriber subscribes to the observable. When the subscription is made, observable calls the subscribers onNext() and onComplete() methods. If anything goes wrong, onError() is called.

Operators in RxJava

I lied, RxJava has 3 building blocks not just 2. For simplicity I kept it 2 in the beginning. Operators are like methods that helps you handle the transformations. They are used between observables and subscribers. One simple operator is map(). Map helps you transform emitted item into another.

Imagine you need to change the hello world string before the subscriber receives it, and you don’t have control over observable and subscriber is running on main thread. You need an intermediate method to do so. Use map() operator.

Observable.just("Hello ")
    .map(s -> s + "Paras!")
    .subscribe(s -> System.out.println(s));

Note here, the just() method is a built-in Observable creation method. It emits one item. The above code prints “Hello Paras!”

RxAndroid Example

RxAndroid provides a scheduler that runs code in main thread of Android. With this, You can define a observable that runs code in background thread and sends the results to main thread to take action. This is alternative to using AsyncTask in Android.

Observable<String> getTheString = Observable.create(emitter -> {
        SystemClock.sleep(1000); // some delay
        emitter.onNext("Hello World");
        emitter.onComplete();
});

getTheString.observeOn(AndroidSchedulers.mainThread())
           .subscribeOn(Schedulers.io())
           .subscribe(string -> {
                textView.setText(string);
           })

All the Power to You!

Now that you have too learnt RxJava, the power is yours now. You can use it to anything in Android. The most obvious case you want to use RxJava would be for API Calls. And because RxJava handles the threading, you can write code and sit back and relax. Ofcourse, there’s more to RxJava, which you can continue learning. Now, Try finding out how to use Retrofit with RxJava. All the power to you.

Sharing options: