How to create RXjs RetryWhen with delay and restriction of attempts

I am trying to make an API call (using angular4) that repeats when it fails using retryWhen. I want it to linger for 500 ms and try again. This can be achieved with this code:

loadSomething(): Observable<SomeInterface> { return this.http.get(this.someEndpoint, commonHttpHeaders()) .retryWhen(errors => errors.delay(500)); } 

But it will continue all the time. How to limit this, say, 10 times?

Thanks!

+24
angular observable rxjs
source share
2 answers

You need to apply a restriction to the retry signal, for example, if you want only 10 retries:

 loadSomething(): Observable<SomeInterface> { return this.http.get(this.someEndpoint, commonHttpHeaders()) .retryWhen(errors => // Time shift the retry errors.delay(500) // Only take 10 items .take(10) // Throw an exception to signal that the error needs to be propagated .concat(Rx.Observable.throw(new Error('Retry limit exceeded!')) ); } 

EDIT

Some commentators have asked how to make sure that the last error is thrown. The answer is a little less clear, but no less effective, just use one of the smoothing map operators (concatMap, mergeMap, switchMap) to check which index you belong to.

Note. Using the new RxJS 6 pipe syntax for further validation (this is also available in later versions of RxJS 5).

 loadSomething(): Observable<SomeInterface> { const retryPipeline = // Still using retryWhen to handle errors retryWhen(errors => errors.pipe( // Use concat map to keep the errors in order and make sure they // aren't executed in parallel concatMap((e, i) => // Executes a conditional Observable depending on the result // of the first argument iif( () => i > 10, // If the condition is true we throw the error (the last error) throwError(e), // Otherwise we pipe this back into our stream and delay the retry of(e).pipe(delay(500)) ) ) return this.http.get(this.someEndpoint, commonHttpHeaders()) // With the new syntax you can now share this pipeline between uses .pipe(retryPipeline) } 
+52
source share

Use

 .retry(3) 

Repeats the observed source sequence a specified number of times or until it completes successfully.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/retry.md

-6
source share

All Articles