RxJava Operators: doOnNext(), doAfterNext(), doOnComplete(), doOnError()

October 31, 2018

doOnNext()

The doOnNext() operator can be used for side-effects in the operator chain. This operator does not affect or transfer the emission, but let’s us to take a peek at the emission.
One possible use is to include logging:

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "bb", "ccc", "dddd", "eeeee");

        myObservable.doOnNext(x -> System.out.println(String.format("About to process emission: '%s'", x)))
                    .map(String::length)
                    .subscribe(System.out::println);
    }
}

doAfterNext()

A rather similar operator is doAfterNext() it performs the same role as doOnNext(), but it is called after the emission is passed downstream:

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "bb", "ccc", "dddd", "eeeee");

        myObservable.doAfterNext(x -> System.out.println(String.format("Above result is for emission: '%s'", x)))
                    .map(String::length)
                    .subscribe(System.out::println);
    }
}

doOnComplete()

The doOnComplete() operator is called when the onComplete() is called. It could be helpful to see which are the points in the operator chain where the Observable has onComplete() calls.

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "bb", "ccc", "dddd", "eeeee");

        myObservable.doOnComplete(() -> System.out.println("doOnComplete() was called!"))
                    .map(String::length)
                    .subscribe(System.out::println,
                               Throwable::printStackTrace,
                               () -> System.out.println("onComplete() was called!"));
    }
}

doOnError()

Since RxJava is using operator chains with lambda expressions, it can be more complex to debug. On top of the operators above, the doOnError() operator could be useful to place between other operators to see which one is causing an error:

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.just(7, 5, 2, 0, 3, 9);

        myObservable.map(x -> x * 2)
                    .doOnError(e -> System.out.println("Multiplication failed!"))
                    .map(x -> 100 / x)
                    .doOnError(e -> System.out.println("Division failed!"))
                    .subscribe(x -> System.out.println("Received: " + x),
                               e -> System.out.println("Error: " + e));
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami