Libraries

RxJava, RxAndroid Tutorials

What is reactive programming ?

The RxJava is a very interesting and new topic in Android development. But problem is that it is not easy to understand. Especially, Functional reactive programming is very hard to understand when you come from Object-Oriented Programming

Reactive is a programming paradigm and the oriented around data flow and propagation of data change. Any things can be stream variables such as user input, properties, and data structure etc. For instance RSS feed, and any click event. We can listen to these streams and reacting accordingly.

Now, what is ? Apps increasingly to complete better interactive experiences to the user. Reactive programming is phenomena that works and build a creating app that full-fill that user expectation

Now comes comes what is streams .?  

The stream is a sequence of ongoing event ordered in time. A stream can emit three different things a Value, an Error, and Completed signal.   We capture these emitted events by defining the specific function by executing each instance.

The listening each stream is called Subscriber. The functions we define are observers. The stream is subject and observers being observed. This is an observer and observable design pattern.

  • Observable => Emits items
  • Subscriber => Consume those items.

Why should use reactive programming

  • Reactive Programming raises the level of abstraction So we can focus on the interdependent of the code the define business logic rather then having to consistent falling large amount of implementation details.
  • The code in Reactive Programming in likely is more concise and simply the ability to chain asynchronous operations.   
  •  Reactive Programming is exposed explicit way to define how concurrent operation should be operates   
  • App have evolve  to more real time. Suppose one form is hold large data and you doing a single change in fields so data is automatically triggers and save to the backend. So same content is reflected the real time all other connected user
  • It help to reduce the maintenance of the state variables.

RxJava in Android

Rx stands for reactive extension. RxJava is a library for composing asynchronous and event-based programming by using observable sequence.

But what does actually means?

In Reactive programming, we received the continuous flow of data streams and we provide the operation apply to stream. The Source of data doesn’t really matter.

One of the most challenges of writing a robust Android app is a dynamic nature of changing input. In traditional programming, we have to set explicitly on variables them to be updated. If one value change then dependent value is not changed without adding line of code.

// init variables 
int a,b,c;
//init input 
a=1;
b=2;
//set the output value 
c=a+b ;
// Now update the dependent value     
b=5;
c=? // what should c be ..?

So if you want to reflect dependent value you should use callback methods. So basically C variable value is relay on callback. Most importantly Reactive Programming address these kinds of issue by providing a framework to describe output to reflect these changing input

How work RxJava .?

RxJava is a extension library from DotNet enable android app to be built in this style. In this observer design pattern an Observable emits items  and subscriber consume those items. There is pattern how items is emitted and Observable emits any number of items including 0 items then it terminate either by successfully completing or due to an error. Each subscriber have observable call.

It differs in one key way observable even don’t start emitting items until someone explicitly subscribes to them.

RxJava Basics

Now I will discuss building blocks of RxJava. Basically  Rx is made up of three key points

RX = OBSERVABLE + OBSERVER + SCHEDULERS

Observable

Observable are emitted a stream of data and event, It can be 0 or more. it terminates either by successfully completing or due to an error.

 Observable<String> listObservable = Observable.just("Maroon", "Red", "Orange", "Yellow", "Green", "White", "Black", "Blue", "Navy");

Observer

Observer  is class that receives the events or data and acts upon it. In other words, Observers is consumed data stream emitted by observable.

Basically, Observer has 4 interface methods to manage different states of the Observable
  • onSubscribe(): Observers have to subscribe observable using subscribeOn() method to receiving emitted data by observable.
  • onNext(): This method invoked when the observable emits the data all the registered observer receives the data in onNext() callback.
  • onError(): This method invoked when the emission of data is not successfully completed. then an error is thrown from observable, the observer will receive it in onError().
  • onComplete(): This method is invoked when the Observable has successfully completed emitting all items.

Schedulers

As we know RxJava provides a simple way of asynchronous programming. That allows simplifying the asynchronously processing to manage the long-running operation.

In Android development, Thread management is a big nightmare for every developer. Rx programming provides also a simplified way of running different tasks in different threads. Schedulers are the component in Rx that tells observable and observers, on which thread they should run.

Schedulers is  has 2 methods which decide the (observer and observable) which thread should be run

  • observeOn() – Is tell the observers, on which thread you should observe
    • AndroidSchedulers.mainThread() – Observer will run on main UI thread.
  • subscribeOn() – tell the observable, on which thread you should run.
    • Schedulers.io() – will execute the code on IO thread.
    • Schedulers.newThread() – will create new background

In RxJava you can convert the stream in before received by the observers such as if an API call depends on the call of another API Last but not least, Rx programming reduces the need for state variables, which can be the source of errors.

You have to understand 3 basic step in RxJava

  1.  Create observable  –  It emits the data
  2. Create an observer  – it consumes data 
  3. Schedulers – It manages concurrency 

How to implement in Android ?

Let’s understand how particle implement that, Suppose you have a colorist and want to print each color on Logcat using RxJava. So simple fallow above 3 steps.

package com.wave.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Observable<String> listObservable = Observable.  
                //Observable. This will emit the data
                just("Maroon", "Red", "Orange", "Yellow", "Green", "White", "Black", "Blue", "Navy");  
        //Operator

        listObservable.subscribeOn(Schedulers.newThread())  
                //Observable runs on new background thread.
                .observeOn(AndroidSchedulers.mainThread())  
                //Observer will run on main UI thread.
                .subscribe(new DisposableObserver<String>()
                        //Subscribe the observer
                {
                    @Override
                    public void onNext(String s) {
                        Log.d(TAG, "onNext: New data received:  " + s);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "Error received: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "All data emitted.");
                    }
                });
    }
}

Output is –

D/MainActivity: onNext: New data received:  Maroon
D/MainActivity: onNext: New data received:  Red
D/MainActivity: onNext: New data received:  Orange
D/MainActivity: onNext: New data received:  Yellow
D/MainActivity: onNext: New data received:  Green
D/MainActivity: onNext: New data received:  Black
D/MainActivity: onNext: New data received:  Blue
D/MainActivity: onNext: New data received:  Navy
D/MainActivity: All data emitted.

So by now, you should be able to understand, What is RxJava and why we need RxJava, why we need them and how we can implement them. In the next articles, we are going to learn how to use RxJava and it’s operators in detail. such as concat two APIs details

Leave a Reply

avatar
  Subscribe  
Notify of