ReactiveX in Android

Posted By : Rahul Baboria | 04-Dec-2017

Android application have UI interactions, network calls , etc which results in callbacks hub means there are so many callbacks like from one activity to another class and from other class to other activity. ReactiveX provides a way to handle callbacks and events with more precised way.

 

Setup :

To use RxAndroid in your Android studio project . Add the following dependency in Gradle :

'compile 'io.reactivex:rxandroid:0.25.0'

 

CONCEPT :

In ReactiveX there are two main parts , Observables and Observers . We can say that observables are those objects which emits data and observers are those who receives that data and processes. Basically RxJava and RxAndroid are same conceptual wise , observers are instances of Observer interface and observables are instances of Observale class.

 

Observables :

To create observable that emits single object , we can use just keyword . Like:

Observable<String> myFirstObservable 
    = Observable.just("Oodles Technologies"); // Emits "Oodles Technologies"

To emit observable's data , there should be atleast one observer that is subscribed to it , otherwise it is useless. To create observer we have to implement a Observer interface and ovrride basically its three methods :

1. onCompleted()
2. onError(Throwable e)
3. onNext(String s)
 
 

Observer<String> myFirstObserver = new Observer<String>() {
    @Override
    public void onCompleted() {
        // Called when the observable at end of data emitting.
    }
 
    @Override
    public void onError(Throwable e) {
        // Called when the observable throws an error
    }
 
    @Override
    public void onNext(String s) {
        // Called when observable emits data each time
        Log.i("Inside Observer onNext()", s);
    }
};

 

Further we have to use subscriber to assign an observer to an observable.

 

Subscription mySubscription = myObservable.subscribe(myFirstObserver);

There are some cases in which we don't have to use onError and onCompleted methods , we can use Action1 interface there which contains onle one method which is called everytime observable emits data.

Action1<String> newAction = new Action1<String>() {
    @Override
    public void call(String str) {
        Log.d("Inside New Action Call", str);
    }
};

To use this action object as an observer or to subscribe it to an observale, we have to pass it as

 

Subscription mySubscription = myObservable.subscribe(myAction1);

 

If we want deattach the observer from observable , we have unsubscribe that particular subscription.

 

mySubscription.unsubscribe();

 

Operators in RxAndroid:

If we want to create complex observable objects we have there are keywords like from as mention in example below :

Observable<Integer> myArrayObservable 
    = Observable.from(new String[]{"Java", "JSON", "XML", "PYTHON", "RUBY", "GRAILS"}); // Emits items one after another
 
myStringArrayObservable.subscribe(new Action1<Integer>() {
    @Override
    public void call(String lang) {
        Log.d("Inside Action1", lang); // 
will print the string
    }
});

 

ReactiveX have Operators like map and filters also .  Java 7 doesn’t supports lambdas and higher-order functions, we’ll have to do it with classes that simulate lambdas. In order to simulate a lambda which takes one argument, you will have to create a class that implements Func1 interface.

 

myArrayObservable = myArrayObservable.map(new Func1<Integer, Integer>() { // Input and Output are both Integers
    @Override
    public Integer call(Integer integer) {
        return integer * integer; // Squares the number
    }
});

 

Map operator doesn't effects previous observable as it creates a new observable each time. When we subscribe to new observable i.e myArrayObservable , it will create new observable and result of it will be square of integers.

There are filters as well as such as skip operator where we can skip calls like if we receiving first call response we want to skip that and want to consider second , it can be done like:

 

myArrayObservable
    .skip(1) // Skip the first item
    .filter(new Func1<Integer, Boolean>() {
        @Override
        public Boolean call(Integer integer) { // Ignores every item that returns false
            return integer % 2 == 0; 
        }
    });
 
// Emits 2,4 and 6

 

Thanks.

About Author

Author Image
Rahul Baboria

Rahul Baboria is having good knowledge over Android Application.

Request for Proposal

Name is required

Comment is required

Sending message..