onErrorReturn – return a default value on error
The onErrorReturn
provides you with a technique to specify a default value to return to the downstream in case an error occurred in the upstream. Take a look at the following code snippet:
fun main(args: Array<String>) { Observable.just(1,2,3,4,5) .map { it/(3-it) } .onErrorReturn { -1 }//(1) .subscribe { println("Received $it") } }
We used the onErrorReturn
operator to return -1
whenever an error occurs. The output is as follows:
As we can see in the output, the onErrorReturn
operator returns the specified default value. The downstream didn't receive any item further as the upstream stopped emitting items as soon as the error occurred.
Note
As we mentioned earlier, both onError
and onComplete
are terminal operators, so the downstream stops listening to that upstream as soon as it receives any of them.