Retrying on error

The retry operator is another error handling operator that enables you to retry/re-subscribe to the same producer when an error occurs. You just need to provide a predicate or retry-limit when it should stop retrying. So, let's look at an example:

    fun main(args: Array<String>) { 
      Observable.just(1,2,3,4,5) 
        .map { it/(3-it) } 
        .retry(3)//(1) 
        .subscribeBy ( 
            onNext  = {println("Received $it")}, 
            onError = {println("Error")} 
         ) 
         println("\n With Predicate \n") 
        var retryCount = 0 
        Observable.just(1,2,3,4,5) 
        .map { it/(3-it) } 
        .retry {//(2) 
           _, _-> 
           (++retryCount)<3 
        } 
        .subscribeBy ( 
           onNext  = {println("Received $it")}, 
           onError = {println("Error")} 
        ) 
    }

On comment (1), we used the retry operator with a retry limit, and on comment (2), we ...

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.