Search code examples
angularrxjsrxjs5angular2-observables

How to use retryWhen with a function that returns a Boolean?


Here's my code:

this._http.post(this._url_get + extension, '', { headers: headers })
    .map(res => res['_body'])
    .retryWhen(errors => {return responseErrorProcess(errors)})

now I need to catch exceptions and pass them to my responseErrorProcess() which returns true if it needs to retry

I could not figure out how to retrieve the exceptions from errors, this is how it looks:

Subject_isScalar: falseclosed: falsehasError: falseisStopped: falseobservers: Array[0]thrownError: null__proto__: Observable`

It doesn't seem to contain errors about the exceptions that occurs, plus I couldn't figure out what should I return in order to actually retry or not.


Solution

  • retryWhen should return an Observable. The retry occurs once that observable emits:

    .retryWhen(errors => 
        //switchMap to retrieve the source error
        errors.switchMap(sourceErr => 
            //send source to processor
            responseErrorsProcess(sourceErr) ? 
            //if result is TRUE, emit (will cause retry). Else, pass on the error
            Observable.of(true): Observable.throw(sourceErr)
        )
    )
    

    If you want to complete instead of error when your processor returns false, replace Observable.throw() with Observable.empty()