In this tutorial, we’ll learn about performing basic RxJava operations in Android. So first of all let’s see what is RxJava and why should we use it in AndroidRxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences.In simple language, we can say that, In most Android applications, we are reacting to user interactions (clicks, swipes and etc.) while doing something else in the background (networking).Combining all these tasks are a somewhat hard thing and we could end up with unmanageable code, which is very hard to understand.For example, sending a request to a database over the network and after it completes start fetching user messages and preferences at the same time, and after all of that is complete show a welcome message or any other UI task.

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

If we are implementing these functionalities using JavaSE in Android, We are going to need to use:

  1. Three or four different Async tasks.
  2. Create a Semaphore, that will wait until both of the requests (settings and messages) will complete
  3. Object-level fields to store the results and interacting with UI.

So we need to play with a locking mechanism to handle all these tasks in Java. All this can be avoided by simply using RxJava. Now let’s see how to use all these in Android.

Here we’ll just see a demo application using the mechanism of RxJava to handle network operations. We do not actually perform any complex operations like the query to online database etc. but at the same time the code explained here can be directly used to perform such operations.

Creating a New Project:

Open your Android Studio & create a new Project, give name whatever you like and We’ll keep all the things by default and clicked finish.

Adding Dependencies to Build.Gradle

In order to use this library, you’ll need following dependencies in your application. So add the following line of dependencies to your build.gradle file, under dependencies block:

compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxjava-async-util:0.21.0'

compile 'io.reactivex:rxandroid:1.1.0'

compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'

compile 'com.trello:rxlifecycle:0.4.0'
compile 'com.trello:rxlifecycle-components:0.4.0'

Now sync your project and it will download all the necessary files.

Now in MainActivity.java, add the following code.

Observable.just("1", "2")
        .subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                System.out.println(s);
            }
        });

For demo purpose, we are executing two tasks: printing “1” and “2”. Here you can replace this printing task with your own heavy networking tasks like fetching photos from the online server or querying to online database etc.

So in technical terms, Observable is a class, which will emit the two tasks or items named 1 and 2 respectively. For detailed understanding refer this link of official documentation of RxJAva: http://reactivex.io/documentation/observable.html 

So as we discussed above, this code will complete both task 1 and 2 first, and then only it will move further for execution of code. Note that this execution will on main UI thread, then also UI will run smoothly. By using this,  we’ve eliminated the use of AsyncTask or any other thread declared explicitly(Also they are of course not main Thread).

Let’s now see some details about the observable class:

Observable is something that you can subscribe to listen for the items that the observable will emit. They can be constructed in many different ways. However, they usually don’t begin emitting items until you subscribe to them.

After you subscribe to an observable, you get a Subscription The subscription will listen for the items from observable until it marks itself as completed or, otherwise, it will continue indefinitely (a very rare case).

Now let’s see how to create a custom Observer, which we can call explicitly when needed. In your mainActivity, replace the old code with the following code:

Observable<String> observable = Observable.create(
    new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("Hi");
            subscriber.onCompleted();
        }
    }
);

Now this is a custom Observer, which will not emit any items until it is called for it (subscribed). So now lets see how to subscribe this observer:

Add following code below:

     observable.subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                System.out.println(s);
            }
        });

on executing this, the observer will be subscribed and will emit “Hi”. Note that here only single task is performed, but you can add more task by “subscriber.onNext()” method as follows:

For example, if you are fetching images from the internet, you can write something like:

subscriber.onNext(new FetchImages());

Note some of the important method used in custom subscribers is explained as follows:

  1. onNext(v) – Send a new value to a subscriber
  2. onError(e) – Notify observer about an error that has occurred
  3. onCompleted() – Let subscriber know that it should unsubscribe as there won’t be any more content from this observable.

Related:

Parse JSON Data using Retrofit and Rxjava in android and display in Recyclerview using cardview

Transfer Files over local WiFi network using Android TCP connection

Connecting To Phone Book, Phone Call, And Default SMS Service using Android

Enable/Disable Wi-Fi programatically in Android Wifi connect

Secure phone contacts on your gmail account

Integrating Observable with Android UI:

Now, this is the most important point. How to subscribe to observers when the button is clicked on text in textViews is changed etc. For that consider the following code:

Button button;

    RxView.clicks(button)
            .subscribe(new Action1<Void>() {
                @Override
                public void call(Void aVoid) {
                    System.out.println("Click");
                }
            });

 

similarly,

    TextView finalText;
    EditText editText;
 
    RxTextView.textChanges(editText)
            .subscribe(new Action1<CharSequence>() {
                @Override
                public void call(CharSequence charSequence) {
                    finalText.setText(charSequence);
                }
            });

This approach using RxJava. You can always use default “setOnclickListener”. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts