Using subscribe()

First of all, the most common way to handle errors and exceptions is to use the .subscribe() method. The .subscribe() method takes an additional argument that is used to process the exceptions that the Observable or operators have thrown.

Let's take an example. Consider this piece of code:

Observable.just("One")
.doOnNext(i -> {
throw new RuntimeException();
})
.subscribe(item -> {
log("subscribe", item);
});

As it is now, it will kill the entire application because there is an exception thrown in the .doOnNext() operator. This can be easily mitigated using the second argument of the .subscribe() method:

Observable.just("One")
.doOnNext(i -> {
throw new RuntimeException();
})
.subscribe(item -> {
log("subscribe", item);
}, throwable -> {
log(throwable);
});

More concisely, it can be done with the following:

Observable.just("One")
.doOnNext(i -> {
throw new RuntimeException("Very wrong");
})
.subscribe(item -> log("subscribe", item), this::log);

 Here, the overloaded .log() method is available with the following body:

private void log(Throwable throwable) {
Log.e("APP", "Error on " + Thread.currentThread().getName() + ":",
throwable);
}

After this gets executed, we will find that the exception was successfully logged as illustrated:

Error on main:
java.lang.RuntimeException: Very wrong

As we can see, this is a very simple and straightforward way to handle errors. Also, this is usually one of the best, fail-safe ways to handle exceptions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.8