The error handling operators
We already learned about the onError
event in the Subscriber/Observer. However, the problem with the onError
event is that the error is emitted to the downstream consumer chain, and the subscription is terminated instantly. For example, take a look at the following program:
fun main(args: Array<String>) { Observable.just(1,2,3,5,6,7,"Errr",8,9,10) .map { it.toIntOrError() } .subscribeBy ( onNext = { println("Next $it") }, onError = { println("Error $it") } ) }
The output of the program is shown in the following screenshot:
The program throws an exception in the map
operator when the string Errr is emitted from the Observable. The exception was caught by the onError
handler, but the Subscription doesn't get any further emissions.
This may not be the desired behavior every time. Although we cannot pretend the error never happened and continue...