rxjs Retry and RetryWhen Operators 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.
    .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;