Introducing Operators in RxJava tutorial for beginners

Checkout the previous post here

Here’s how we’re going to solve the item transformation problems: with operators. Operators can be used in between the source Observable and the ultimate Subscriber to manipulate emitted items. RxJava comes with a huge collection of operators, but its best to focus on just a handful at first.

For this situation, the map() operator can be used to transform one emitted item into another:

Observable.just("Hello, world!")
    .map(new Func1() {
        @Override
        public String call(String s) {
            return s + " -Dan";
        }
    })
    .subscribe(s -> System.out.println(s));

Again, we can simplify this by using lambdas:

Observable.just("Hello, world!")
    .map(s -> s + " -Dan")
    .subscribe(s -> System.out.println(s));

Pretty cool, eh? Our map() operator is basically an Observable that transforms an item. We can chain as many map() calls as we want together, polishing the data into a perfect, consumable form for our end Subscriber.

 

More on map()

Here’s an interesting aspect of map(): it does not have to emit items of the same type as the source Observable!

Suppose my Subscriber is not interested in outputting the original text, but instead wants to output the hash of the text:

Observable.just("Hello, world!")
    .map(new Func1() {
        @Override
        public Integer call(String s) {
            return s.hashCode();
        }
    })
    .subscribe(i -> System.out.println(Integer.toString(i)));

Interesting – we started with a String but our Subscriber receives an Integer. Again, we can use lambdas to shorten this code:

Observable.just("Hello, world!")
    .map(s -> s.hashCode())
    .subscribe(i -> System.out.println(Integer.toString(i)));

Like I said before, we want our Subscriber to do as little as possible. Let’s throw in another map() to convert our hash back into a String:

Observable.just("Hello, world!")
    .map(s -> s.hashCode())
    .map(i -> Integer.toString(i))
    .subscribe(s -> System.out.println(s));

Would you look at that – our Observable and Subscriber are back to their original code! We just added some transformational steps in between. We could even add my signature transformation back in as well:

Observable.just("Hello, world!")
    .map(s -> s + " -Dan")
    .map(s -> s.hashCode())
    .map(i -> Integer.toString(i))
    .subscribe(s -> System.out.println(s));

Checkout the sample Here

Categories: RxJava2

Leave a Reply

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

Social Media Auto Publish Powered By : XYZScripts.com