Avoid Boilerplate code by RxJava Tutorial

Checkout the previous post here 

That’s a lot of boilerplate code just to say “Hello, world!” That’s because I took the verbose route so you could see exactly what’s happening. There are lots of shortcuts provided in RxJava to make coding easier.

First, let’s simplify our Observable. RxJava has multiple built-in Observable creation methods for common tasks. In this case, Observable.just() emits a single item then completes,

Observable myObservable =
    Observable.just("Hello, world!");

Next, let’s handle that unnecessarily verbose Subscriber. We don’t care about onCompleted()nor onError(), so instead we can use a simpler class to define what to do during onNext():

Action1 onNextAction = new Action1() {
    @Override
    public void call(String s) {
        System.out.println(s);
    }
};


Actions can define each part of a Subscriber. Observable.subscribe() can handle one, two or three Action parameters that take the place of onNext(), onError(), and onComplete(). Replicating our Subscriber from before looks like this:

myObservable.subscribe(onNextAction, onErrorAction, onCompleteAction);

However, we only need the first parameter, because we’re ignoring onError() and onComplete():

myObservable.subscribe(onNextAction);
// Outputs "Hello, world!"

Now, let’s get rid of those variables by just chaining the method calls together:

Observable.just("Hello, world!")
    .subscribe(new Action1() {
        @Override
        public void call(String s) {
              System.out.println(s);
        }
    });

Finally, let’s use Java 8 lambdas to get rid of that ugly Action1 code.

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

If you’re on Android (and thus can’t use Java 8), I highly recommend using retrolambda; it will cut down on the verbosity of your code immensely.

Checkout for more info 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