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 (we should not do this either), there should be a way to at least resubscribe or switch to an alternate source producer.

Error handling operators help you achieve the same.

The following are the error handling operators.

  • onErrorResumeNext( )
  • onErrorReturn( )
  • onExceptionResumeNext( )
  • retry( )
  • retryWhen( )

We will cover error handling operators in detail in Chapter 6, More on Operators and Error Handling.

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

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