RxJava2 in Android Part2

In my last tutorial, We learned basic of Rx Observable and Observer. We learned how Observable and observer works together. If you still not checked then please visit here to get details: RxJava2 in Android Part1.

In this article, I am focusing about Rx (Reactive programming). So question now What is Rx? Rx means Reactive Extensions It means anything change happens it will react something. Rx Functionality is hard to understand initially if you from basic java, But believe me it is really awesome because it gives the good result. 

Let's check the basic hello world programming in Android with Rx. Rx is basically standard Observer pattern. Observable emit the data and Observers consume the data. To emit the data Observers should subscribe. 
Observable observable = Observable.just("Hello World");
observable.subscribe(observer);
Here Observer should subscribe to consume data.
   
 Observer observer = new Observer() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object value) {
            Toast.makeText(MainActivity.this, (String)value, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(MainActivity.this, "Error "+e, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onComplete() {
            Toast.makeText(MainActivity.this, "Completed", Toast.LENGTH_LONG).show();
        }
    };

Now Question Why RxJava in Android?

In general android programming, we used many callback and event to complete the task. It's really hard to understand for beginner developers. Even I also not like personally to used many callbacks.
For example, We have a fragment that contains listview or recycler view, In adapter class, we  used callback while click on any item view to update something.

Let me take another example in simple word, We used AlertDialog with Cancel and  Okay button option. The user can do click either okay or cancel button. Here also we used callback while clicking on any button to perform the action that notifies to update accordingly. 

Here I am creating an interface  DialogListener for using the callback.


package com.sunil.rxjavaexample.utils;

/**
 * Created by sunil on 18-02-2017.
 */

public interface DialogListener {

    void onPositiveButtonClick();
    void onNegativeButtonClick();
}

DialogUtil is the class that contains all kind of dialog that used in your app.
package com.sunil.rxjavaexample.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

/**
 * Created by sunil on 18-02-2017.
 */

public class DialogUtil {

    public static void showDialog(Context context, String title, String message, final DialogListener dialogListener){
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialogListener.onPositiveButtonClick();
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialogListener.onNegativeButtonClick();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }
}
And I want to show dialog while clicking on a button. Here you can get your callback return. Now you can see this is hard to understand to everyone.

final DialogListener dialogListener = new DialogListener() {
            @Override
            public void onPositiveButtonClick() {
                Toast.makeText(MainActivity.this, "Positive Clicked", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNegativeButtonClick() {
                Toast.makeText(MainActivity.this, "Negative Clicked", Toast.LENGTH_LONG).show();
            }
        };

        Button button = (Button)findViewById(R.id.alertButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtil.showDialog(MainActivity.this, "Rx Alert", "Are you love this Rx?", dialogListener);


            }
        });
Now lets the same thing check with Rx Java using. Let's create one more method in DialogUtil with name showDialogRx(). I subscribe my observer same way as above in Hello World program as we see.
  public static void showDialogRx(final Context context, final String title, final String message, final Observer observer) {

         Observable.create(new ObservableOnSubscribe() {
             @Override
             public void subscribe(final ObservableEmitter e) throws Exception {
                 final AlertDialog ad = new AlertDialog.Builder(context)
                         .setTitle(title)
                         .setMessage(message)
                         .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                             public void onClick(DialogInterface dialog, int which) {
                                 e.onNext(true);
                                 e.onComplete();
                             }
                         })
                         .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                             public void onClick(DialogInterface dialog, int which) {
                                 e.onNext(false);
                                 e.onComplete();
                             }
                         })
                         .create();
                 ad.show();
             }
         }).subscribe(observer);
    }
Now here I want to get the callback return just get the instance of Observer, As like above.
  
 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtil.showDialogRx(MainActivity.this, "Rx Alert", "Are you love this Rx?", observer);

            }
        });
 
    Observer observer = new Observer() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object value) {
            Toast.makeText(MainActivity.this, value.toString(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(MainActivity.this, "Error "+e, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onComplete() {
            Toast.makeText(MainActivity.this, "Completed", Toast.LENGTH_LONG).show();
        }
    };
See this is pretty easy to understand, Here we do not require any interface or instance of an interface. It works automatically all subscribed observers will get notify. This is the one case that we can prefer to use RxJava.

Now Let's take another example to encourage us to use RxJava in building the awesome app. We are using multiple background task in our app to fetch the data from server and display on UI and much more kind of thing we do. To achieve this background task mostly we used async task. But Async task has its own drawback like When your application running multiple async tasks then we do not know which task will be finished first and all.

Async task is running in activity context and it is partially run by background thread and partially run by Main Thread. In case if Android Os will kill your application because of memory not available at that time then Your activity will be destroyed and then the context of activity will be destroyed. But the async task will be running because its half part will be in the background thread. its cause memory leak. Sometimes error handling in Async task is also very dirty.

If you are dealing with Activity and fragment lifecycle by using rxJava then please unsubscribe the Observable emitting to avoid the memory leak.

In Rx java, it is the very stable way we can do or we can switch threads to tell them which thread will be good suite to execute my task. For multiple tasks, you can easily merge your task and cache. This is not the only thing you can do much more with RxJava.
 
     Webservice.getNetworkCall()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String value) {
                   // handle your request or you can merge any thing
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
So now we can get that why should be used RxJava in an Android. this is few things I have pointed but it provides much more and many ways we can use Rxjava in our application to make the awesome app. In my next tutorial, I will focus some more good features of RxJava that we must to used to build the awesome and stable app. Thanks for reading this post.

Comments

Popular posts from this blog

Service LifeCycle

NavigationView Drawer Expandable menu Item in ANdroid

Custom SeekBar (Discrete SeekBar) in android