Error handling in RxJava/RxKotlin

Aanand Shekhar Roy
AndroidPub
Published in
4 min readFeb 14, 2018

--

If you’ve worked with RxJava/RxKotlin, you might be familiar with three methods of a subscriber. onNext , onError and onComplete. In a reactive stream, elements are consumed by onNext first, and onComplete is called when the stream ends. If you encounter any error in onNext, the complete observable chain is abandoned and control is shifted to onError method. So for example, the below code will run perfectly and will provide the output as:

Output:

1
2
3
4
Completed

Now suppose we encounter an exception in onNext, the whole observable chain is dropped. In the below code, we will deliberately induce an exception when the input is 2:

Output:

1
Exception on 2

This is all well and good if you encounter an error in subscriber, but what if you encounter an error in one of the operators above it? It could be in map operator, or in flatMap operator. The point is, what to do if you encounter an error before it makes its way to the subscriber? There are so many things that we can do in RxJava if we encounter an error. The first one we will be talking about is onExceptionResumeNext():

onExceptionResumeNext

To understand this one, we need to know about doOnNext first. You might be thinking, it sounds much like onNext of a subscriber. That’s right! doOnNext is basically for side-effects. The items will go to doOnNext before it gets finally consumed by onNext method of the observer. So doOnNext is a great place for debugging your items in the stream. Now back to onExceptionResumeNext, if we encounter any exception in the observable chain(before they make their way to the observer methods), we can use this method to plug in another

--

--

Aanand Shekhar Roy
AndroidPub

Senior Software Engineer @Joist, Author of Kotlin Programming Cookbook.