Understanding Java: RxJava for beginners
In this article I will explain basics of RxJava though examples. This article is for RxJava beginners. On the other hand, if you already know something about RxJava, this article is good for reviewing your knowledge about Android development.
What is RxJava?
RxJava is a Java VM implementation of ReactiveX a library for composing asynchronous and event-based programs by using observable sequences.
The building blocks of RxJava are Observables and Subscribers. Observable is used for emitting items and Subscriber is used for consuming those items. Maybe some of you will think: „Hmmm this is so similar to standard Observable pattern“.
And yes it is, but RxJava does it much better and has more options. For example, Observables often don’t start emitting items until someone subscribes to them. This is a great feature because this way you should save your performances.
RxJava works like this. Subscriber subscribes to Observable, then Observable calls Subscriber.onNext() for any number of items, if something goes wrong here is Subsciber.onError() and if all finishes fine, here is Subscriber.onCompleted().
You see this is easy!
Shut up! Give me some fancy codes!
Example 1
In this example we will create basic Observable and Subscriber, and then we will link them up, and see what will happen. Spoiler alert! Something awesome…
Let’s create a basic Observable:
Observable myObservable = Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("Blue Factory"); subscriber.onCompleted(); } });
Created Observable emits „Blue Factory“ String and then completes. „Blue Factory“ String will be received on Subscribers onNext() method. Now let’s create Subscriber.
Subscriber<String> mySubscriber = new Subscriber<String>() { @Override public void onCompleted() { System.out.println("I'm done"); } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.println(s); } };
Subscriber receives String value on onNext() method and prints it, also String „I’m done“ prints when onCompleted() methods is called.
Now link them up.
myObservable.subscribe(mySubscriber);
Result:
I/System.out: Blue Factory
I/System.out: I’m done
When subscription happens, myObservable calls mySubscription onNext() and onComplited() methods. Results are outputs „Blue factory“ and “I’m done“, after that everything stops and terminates.
Can I do it more simple?
Of course! You can do it!
You may notice that a creation of myObservable has too much code and it looks messy. RxJava give us some fancy shortcuts.
Some of those shortcuts are methods like Observable.just() and Observable.from();
Observable.just() emits only one single items and Observable.from() emits one item by one from list of items.
Shut up! Give me some fancy code!
Example 2
In this example, we will make the same thing like in Example 1, but now with less code.
Let’s create our new fancy, good looking Observable:
Observable myObservable = Observable.just("Blue Factory");
Wow! It seems that our Observable has lost some weight!
Let’s create Subscriber:
Subscriber mySubscriber = new Subscriber() { @Override public void onCompleted() { System.out.println("I'm done"); } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.println(s); } };
Subscriber is same!
Now link them up, and wait for the magic to happen!
myObservable.subscribe(mySubscriber);
Result:
I/System.out: Blue Factory
I/System.out: I’m done
As you see, we manage to complete our task, and do exactly same thing with less code.
Shut up! Give me some fancy code!
Example 3
In this example, we will do something little bit differently with Observable.from(). The idea is to print strings „Blue“, „Factory“, „Blog“, „Post“.
Let’s remind ourselves what is Observable.from(). Observable.from() receives items list and emits on an item by one, so Observable.from() is exactly what we need!
First, we will create ArrayList with Strings:
ArrayList myStringArray = new ArrayList<>(); myStringArray.add("Blue"); myStringArray.add("Factory"); myStringArray.add("Blog"); myStringArray.add("Post");
Let’s create that Observable.from(), shall we?
Observable myObservable = Observable.from(myStringArray);
As you can see, Observable.from() receives as argument ArrayList loaded with Strings. Now, let’s create Subscriber and link them up, and wait for the magic.
Subscriber mySubscriber = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.println(s); } }; myObservable.subscribe(mySubscriber);
Result:
I/System.out: Blue
I/System.out: Factory
I/System.out: Blog
I/System.out: Post
As you see, we’ve successfully done our task again!
Everything you’ve learned up ‘til now is pure basic tricks, but now we will do some „harder“ tricks!
What are Operators in Rx?
Operators are methods created for solving transformations and handling API calls problems. I will show you one simple example for transformation with Map, and maybe in some further articles examples of handling API calls with Retrofit, RxJava on MVP architectural pattern.
For Example, let’s append our „Blue Factory“ String with „ Blog Post“. We can do it in several ways.
First way:
Observable myObservable = Observable.just("Blue Factory" + " Blog Post");
We can do it in Observable, but Observable is supposed to emit items, not to change them.
Second way:
Subscriber mySubscriber = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.println(s + " Blog Post"); } };
Same story, Subscriber wasn’t supposed to change items.
The solution is to add one more step, by adding Operator.
The operator is one additional step between Observable and Subscriber, where object can be transformed.
So let’s do it the right way!
Shut up! Give me some fancy code!
Example 4
First, let’s create Observable:
Observable myObservable = Observable.just("Blue Factory");
Notice that myObservable emits just one unchanged item.
Now let’s create Operator, for this example best solution is to use Map operator. The Map operator can transform our object in a way we like and return it to Subscriber.
Observable myObservable = Observable.just("Blue Factory") .map(new Func1<String, String>() { @Override public String call(String s) { return s + " Blog Post"; } });
In operators call (String s) method transformation of String „Blue Factory“ is done.
And here is Subscriber:
Subscriber mySubscriber = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.println(s); } };
Result:
I/System.out: Blue Factory Blog Post
This example represents a tiny fraction of what Operators can do. For example, Map operator can be stacked multiple times like in the example below:
Shut up! Give me some fancy code!
Example 5
Observable myObservable = Observable.just("Blue Factory") .map(new Func1<String, String>() { @Override public String call(String s) { return s + " Blog Post"; } }) .map(new Func1<String, String>() { @Override public String call(String s) { return s + " article"; } });
Operators also can change type of emitted item like in the example below:
Shut up! Give me some fancy code!
Example 6
In this example, Observable will emit String “5” and Operator will transform it to the Integer 5. Let’s crate Observable.
Observable myObservable = Observable.just("5")
Notice that myObservable type is Observable and Observable emits String.
Let’s create Map operator!
Observable myObservable = Observable.just("5") .map(new Func1<String, Integer>() { @Override public Integer call(String s) { //transformation happened in line below return Integer.valueOf(s); } });
Notice that Map operator call(String s) method receives String and return Integer.
Let’s crate Subscriber and link them up.
Subscriber mySubscriber = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer s) { System.out.println(s); } }; myObservable.subscribe(mySubscriber);
Subscriber type is the same like Observable type, and Operators returning type (Integer).
Here I show you just a little fraction of the picture. With operator’s you can do everything you want!
And the best part about this is that RxJava has an abundance of different Operators. Here you can check all operators: https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-Observable-Operators.
In conclusion, Operators are powerful for object transformation and data polishing, and after all of this, your code will look nice and clean!
What can I do with RXJava?
You can do everything you want because your Observable can be everything, it can be: String, Integer, API call, click, etc. As you progress like Android developer you will use RxJava mostly for API calls and for android widgets.
RxJava provides easy API handling because you don’t need to worry about threading and you can chain few requests and get the result on a single Subscriber.
With RxJava you can handle some widget behavior for example what widget will do after five times being pressed, or you can create Observable which will emit String every 4 sec from EditText input, and so many other fancy things.
I hope this article gives you the basics of RxJava and I hope you will keep exploring RxJava in the future.