fbpx
Home / RxJava / Introduction to RxJava For Android Developers -Part 2

Introduction to RxJava For Android Developers -Part 2

Introduction

In the previous article we talked about creation, filtering and transforming of observables. We saw how it was awesome. So we are going to talk about the concurrency operators in this article.

When you develop an application, you will need often  to do some tasks in parallel to prevent your app from crashing. Thanks to RxJava ,You can handle multi threading easily .RxJava helps you to avoid the painful handling of multithreading using Java.You just need to define which thread you want to do your task and which thread you want to get the response. Concurrency operators like observeOn() and subscribeOn() make our life easy also schedulers.

Schedulers

Schedulers are used to execute some of work on a certain thread. Schedulers are abstraction of Android and Java threading.When you use scheduler to do task , scheduler will run on one of available threads of  thread pool(collection of threads that are ready to use).We can choose which thread using the operators observeOn() and subscribeOn().

There are many types of schedulers that you can use in RxJava. But I will list the most greatly used ones as follows:

AndroidSchedulers.mainThread() This type creates scheduler which will execute its task on Android Main Thread. We often use it to get response for observer.

Schedulers.io() This type creates and returns scheduler for I/O operations like reading/writing over database and network calling.These tasks are not CPU intensive.

Schedulers.newThread() This type creates a new thread to do the task and return scheduler .You should take care when you use this type because the new thread will not be reused after the task finished and it will be destroyed.

Schedulers.computation() This type creates scheduler for CPU intensive operations like image filtering, complex  calculations. It uses the CPU cores so you should be careful when you use it.

Now ,we will talk about subscribeOn() and observeOn() operators.

subscribeOn() Operator This operator tells the scheduler to do the task on observable upstream and then send response to observer on the same thread.You should not use multiple of subscribeOn() on the same chain for observable. Because your chain will choose the closets one to the observable source as follows

// this has effect   
Observable.create(data()).subscribeOn(Schedulers.computation())         
.subscribeOn(Schedulers.io()) // this has no effect

Let us see example for subscribeOn()

 private void showFunctionOfSubscribeOn(){

Observable.just(100, 200, 300) .subscribeOn(Schedulers.newThread()) .subscribe(getObserver()); }

private io.reactivex.Observer getObserver(){

 io.reactivex.Observer observer = new io.reactivex.Observer() {

 @Override public void onSubscribe(Disposable d) {

 Log.e(TAG, "onSubscribe" + Thread.currentThread().getName()); }

}

here we used Scheduler.newThread() to do task in another thread.Although we call subscribe on main thread but the observable worked on another thread. ObserveOn() Operator The main function of observerOn() is to switch the emission of observable to another thread or scheduler.We use this operator to tell downstream consumers to receive the subsequent emissions.Unlike subscribeOn operator, when you put observeOn operator you will affect the thread that observable uses.

RxBinding

Now we learned about some  RxJava2 operators related to Multithreading .We saw how to handle multiple threading using observeOn and subscribeOn and how to use schedulers according to our needs. But what about your UI events ,How many  times you implement OnclickListener or TextWatcher for EditText and your code had  a lot of anonymous classes.Here RxBinding appears on the scene. RxBinding is a set of libraries that helps you to handle user interface events through reactive paradigm.RxBinding enables you to convert any Android view event into Observable.To integrate RxBinding  for you code put the following in build.gradle for your app module.

 Implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
 Implementation 'io.reactivex.rxjava2:rxjava:2.0.8' 
 Implementation 'com.jakewharton.rxbinding2:rxbinding:2.0.0'

If you want to work with lambda expression add the following:

     defaultConfig {    

                    jackOptions {    

                            enabled true 

                        }    
      }   

       compileOptions {    

               sourceCompatibility JavaVersion.VERSION_1_8    

              targetCompatibility JavaVersion.VERSION_1_8    

 }

Now , let us see some examples for RxBinding: Button Example

 private Disposable loginBtnSub;

loginBtnSub = RxView.clicks(loginBtn).subscribe(new Consumer() {

                   @Override public void accept(@NonNull Object o) throws Exception {

                               Toast.makeText(MainActivity.this, "Hi, Mahmoud ", Toast.LENGTH_SHORT).show();

      } });

 

We implemented the handling of click listener for button using subscription and we unsubscribe for it on onDestroy method.

 @Override

 protected void onDestroy() {   

            super.onDestroy();

              loginBtnSub.dispose(); 

}


EditText Example

 edtUsernameSub = RxTextView. textChanges(edtUsername) .subscribe(new Consumer() { 

                              @Override public void accept(@NonNull CharSequence charSequence) throws Exception {                                                                                                 if(charSequence.toString().equalsIgnoreCase("mahmoud"))

                                                         Toast.makeText(MainActivity.this, "Hi mahmoud", Toast.LENGTH_SHORT).show();

 } });

@Override

 protected void onDestroy() { 

super.onDestroy(); edtUsernameSub.dispose();

 }


Now , I know that you see there is no big different than the traditional way of listeners handling for views. But this is not true because the RxBinding gives you more options than the traditional way for instance convert any event to observable .Then, imagine what you can do on it like different operators to facilitate your coding .Also RxBinding gives you systematic way to deal with different views than many ways of view listeners in android.I hope you enjoy this article please share it with your friends and leave you opinion  about this article as comment

About admin

Leave a Reply

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