6

this is my code:

this._api.getCompanies().subscribe(
    res => this.companies = JSON.parse(res),
    exception => {if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() } }
)

in case an exception happened, it will be sent to a function in the API then return true if the problem is fixed (like token refreshed for example) and it just needs to retry again after its fixed

I could not figure out how to make it retry.

2 Answers 2

6

In your .getCompanies() call right after the .map add a .retryWhen:

.retryWhen((errors) => {
    return errors.scan((errorCount, err) => errorCount + 1, 0)
                 .takeWhile((errorCount) => errorCount < 2);
});

In this example, the observable completes after 2 failures (errorCount < 2).

3
  • I'm not sure about how errors looks like. I think it's an array of exceptions (maybe?). So you could extend the takeWhile condition to: errorCount < 2 && this._api.responseErrorProcess(errors[0]) Oct 21, 2016 at 11:38
  • 1
    this is what I was gonna ask, I'll check it up thank you a lot :) actually this way I can centralize the error handling from the api directly, instead of adding the exception in each subsribtion, thank you.! Oct 21, 2016 at 11:41
  • 2
    You could add a console.log(errors) before the return to see how it's structured. Oct 21, 2016 at 11:41
0

You mean something like this?

this._api.getCompanies().subscribe(this.updateCompanies.bind(this))

updateCompanies(companies, exception) {
    companies => this.companies = JSON.parse(companies),
    exception => {
        if(this._api.responseErrorProcess(exception)) {
            // in case this retured TRUE then I need to retry()
            this.updateCompanies(companies, exception)
        }
    }
}
3
  • well I thought there's a way to retry() the observable natively from rxjs, but this would work too thanks . Oct 21, 2016 at 11:26
  • 1
    Be aware, that this example can possibly deadlock. Oct 21, 2016 at 11:27
  • 1
    After a closer look, this also doesn't retry the actual call to the server, just calls the callback function :D Oct 21, 2016 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.