Retry and RetryWhen Operators

Other topics

Retry with backoff, until success or max number of attempts reached

The following code will attempt to execute loadFromHttp() up to 5 times (maxAttempts), with each attempt delayed by as many seconds. If maxAttempts is surpassed, the Observable gives up.

    // assume loadFromHttp() returns a Promise, which might fail.
    Rx.Observable.from(loadFromHttp())
    .retryWhen((attempts) => {
        let maxAttempts = 5;

        Rx.Observable.range(1, maxAttempts+1).zip(attempts, (i, attempt) => [i, attempt])
        .flatMap(([i, attempt]) => {
            if (i <= maxAttempts) {
                console.log(`Retrying in ${i} second(s)`);
                return Rx.Observable.timer(i * 1000);
            } else {
                throw attempt;
            }
        })
    })

Syntax:

  1. .retry(n: number): Observable
    • n: retry will attempt the source Observable this many times.
  2. .retryWhen(receives: notificationHandler, the: scheduler): Observable
    • receives: an Observable of notifications which the use can complete or error.
      • If the 'receives' Observable returns cleanly (completes) the source Observable will be reattempted.
      • If the 'receives' Observable returns an error, the source Observable is aborted.
    • scheduler: The source Observable is subscribed to this scheduler.

Contributors

Topic Id: 9026

Example Ids: 28040

This site is not affiliated with any of the contributors.