Introduction to RxJava for Android Developers

Mahmoud Ramadan
7 min readOct 25, 2018

Introduction

In this Post I am going to talk about RxJava for android.RxJava is one of the hottest topics nowadays because of its advantages over the classic way for android developing. RxJava is a library that allows us to represent any operation as an asynchronous data stream that can be created on any thread, declaratively composed, and consumed by multiple objects on any thread.

These data streams don’t necessarily have to take the form of traditional data types. RxJava treats every thing as stream of data for example variables to properties, caches, and even user input events like clicks and swipes.

The data emitted by each stream can either be a value, an error, or a “completed” signal, although you don’t necessarily have to implement the last two. Once you’ve created your data-emitting streams, you combine them with reactive objects that consume and then act on this data, performing different actions depending on what the stream has emitted.

RxJava has three core components:

  • Observable
  • Observer
  • Subscription

There are a lot of operators that manipulate data like mapping, filtering ..etc .Also there are schedulers where you can choose which thread you want to do your task and which other you will get the response .

If you want to learn more I have Master Class on RxJava on Udemy and this is your 90% Discount

To clear the idea behind RxJava ,Look at this picture for a moment

you will notice that there are a bunch of data (circles,diamonds and triangles) emitted by Observable and there is a filter (Operator)in the middle to filter data (shapes) according to some value(circle shape) and in the end you will get the filtered data in another level(Observer).So the main function of Observable is to observe for data and emit the data continuously .Also the main function of operator is to control the observable .Finally ,the main function of Observer is to get data in its configured thread when it subscribe for it .

Imperative vs Reactive Programming

Let us make small comparison between the old fashion of Java and the RxJava style:

Example :Find the Odd Number in list of integers The Java Style Like this:

public class data {static List data;public static void main(String[] args) {     printOddNums();}private static void printOddNums(){  data = new ArrayList();  data.add(1);  data.add(2);  data.add(3);  data.add(4);  data.add(5);  data.add(6); for (int i = 0; i < data.size(); i++) {
if(!(i%2==0))
System.out.println(i +"is ODD Number");
}
} }

We defined here an array list of integers and we make looping over the integers to check if integer number is odd to be printed.Now, The RXJava Style Like this:

Observable observable =Observable.just(1, 2, 3, 4, 5,6) .filter(new Func1<Integer, Boolean>() { 
@Override public Boolean call(Integer integer) {
//check if the number is odd? If the number is odd return true, to emmit that object.
return integer % 2 != 0;
} });
Observer observer = new Observer() {
@Override public void onCompleted() {
System.out.println("All data emitted.");
}
@Override public void onError(Throwable e) {
System.out.println("Error received: " + e.getMessage());
}
@Override public void onNext(Integer integer) {
System.out.println("New data received: " + integer);
} };
Subscription subscription = observable .subscribeOn(Schedulers.io()) //observable will run on IO thread
.observeOn(AndroidSchedulers.mainThread()) //Observer will run on main thread. .subscribe(observer); //subscribe the observer

We defined here an observable to list of integers and we make filtering using operator called filter to filter the emitted integers for checking if them are odd to be printed or not.We defined observer to get emitted integers in OnNext method one by one and we printed it.We also defined the subscription object to enable observer to subscribe to steam to get integers in UI Thread and to enable observable to do his operation in IOThread.

I would like to say that RxJava is very useful component and it adds new way of thinking while coding.You can use RxJava every where in your code for example you can make timing tasks, Rest API Calls,background tasks, many dependent tasks ,functional programming and more.

RxJava 2 vs RxJava 1

RxJava has powerful operators for different tasks ,it seems that there is no operation you can not do it with RxJava. RxJava is a reactive library for the JVM that can help you to build data reactive apps.

Before we go deeply in this topic let us know what is the difference between RxJava2 and RxJava1.To know more about this, please see this on RxJava Repository on GitHub .To summarize the difference ,You can say that RxJava2 is well written reactive programming library.RxJava2 is written from scratch on the top of Reactive concepts.It has better performance over RxJava1 and better memory management.

Introduction to RxJava Operators :

RxJava Operator is a way to convert your Observable from form shape to another. RxJava has enormous number of operators.No one expects you to memorize this list but it is worth to read them.You will find often an operator for every transform or change in your data.If you did not find some operator, you can do some operations on your observable until you get the desired operator.

In this article I will not cover all operators in RxJava but I will talk about the most popular and greatly used in work.The first thing is to add Rxjava2 dependency in Cradle file.Please check latest version from GitHub repository.

Implementation 'io.reactivex.rxjava2:rxjava:2.0.5'

There are Categories for RxJava operators .I am going to talk about some of them like Observable

  • creation operators
  • Filtering operators
  • combing operators
  • concurrency operators

Observable Creational Operators control the creation of observable like emitting some of objects one by one ,emitting array of objects, emitting object one by one after some delay ,emitting range of items sequentially and more.These are some of creation observable operators and their usage with examples:

Just is an operator which convert an object or several objects into an Observable that emits that object or those objects with out change of data like the following:

private Observable createObserableUsingJust(){ return Observable.just(1,2,13,43,50); }

The output of this method is observable object which emits the values of Just arguments one by one.

From is an operator which converts an Iteratable, a Future, or an Array into an Observable like the following :

private Observable createObserableUsingForm(){ return Observable.fromArray(new Integer[]{10,20,30,40,50}); }

The output of this method is observable object emits the array values one after another like Just operator.You will find more form operators like fromArray,fromFuture,fromIterable …etc.

Interval is an operator which creates an Observable that emits a sequence of integers spaced by a given time interval like the following:

private Observable createObservableUsingInterval(){ return Observable.interval(0,2, TimeUnit.SECONDS); }

Filtering Operators The main goal of these operators is to filter stream according to some condition to emit some objects like the following:

Filter is an operator which filter items emitted by Observable like the following:

private Observable filter(){ return Observable.just(1,2,3,4,5,6,7,8) .filter(new Predicate() { @Override public boolean test(Integer num) throws Exception { return num%2==0; } }); }

The output of this method is observable with even numbers only because we apply filter operator on number sequence.

Skip

is an operator which ignores the first n items emitted by observable.

private Observable showFunctionOfSkip(){ return Observable.fromArray(new Integer[]{1,2,3,4,5,6,7,8}) .skip(2); }

The output of this method is observable which contains numbers started from 3 to 8 and numbers 1,2 will be skipped.

Take

is an operator which emits the first n items of observable

private Observable showFunctionOfTake(){ return Observable.fromArray(new Integer[]{1,2,3,4,5,6,7,8}) .take(2); }

The output of this method is observable with 1,2 numbers only.

Combing Operators The main goal of these operators is to combine two different sources of streams and emit them as a single source.And these are some of them:

Merge is an operator which combines multiple observable into one.

private Observable showFunctionOfMerge(){
String [] myName ={"Mahmoud","Ramadan","Abd","elwahed"} ;
String [] myJob ={"I am ","Software Engineer"};
Observable myNameObservable= Observable.fromArray(myName);
Observable myJobObservable= Observable.fromArray(myJob);
return Observable.merge(myNameObservable,myJobObservable);
}

Note:merge does not guarantee that the order of emitted data by observable unlike concat operator.

Zip is an operator which combines sets of items emitted by two or more Observable together via a specified function and emit items based on the results of this function class Custom Object{ int number; String ch; }

private Observable showFunctionOfZip(){Observable<Integer> numObservable = Observable.fromArray(new Integer[]{11, 22, 33, 44, 55});  //Emits integers
Observable<String> chObservable = Observable.fromArray(new String[]{"S", "O", "O", "N",}); //Emits characters
return Observable.zip(numObservable, chObservable, new BiFunction<Integer, String, CustomObject>() {
@Override
public CustomObject apply(Integer integer, String s) throws Exception {
CustomObject customObject = new CustomObject();
customObject.number=integer;
customObject.ch = s;
return customObject;
}
});
}

Transforming Operators The main goal of these operators is to transform emitted data by Observable like the following:

map is an operator which transforms the items emitted by an Observable by applying a function to each of them

private Observable showMapFunction(){ return Observable.just(1,2,3,4,5) .map(
new Function() {
@Override public Object apply(Object ob) throws Exception { return (Integer)ob*10; } });
}
.

The output of this method is observable which its emitted values are multiplied with 10 . In the next Article I will continue the explanation of the rest operators.Please if you find this article helpful share it to your friends and give me your feedback through commenting on this article.

--

--