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 ...

Get Reactive Programming in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.