Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
exponential-backoff-retry.ts
import { Observable, pipe, range, throwError, zip, of, timer } from 'rxjs';
import { map, mergeMap, retryWhen } from 'rxjs/operators';
export const RETRY_COUNT = 3;
export const RETRY_TIME = 500;
export function exponentialBackoffRetry<T>(
maxTries: number = RETRY_COUNT,
delay: number = RETRY_TIME,
) {
return pipe<Observable<T>, Observable<T>>(
retryWhen(errors => {
return zip(range(1, maxTries + 1), errors).pipe(
mergeMap(([i, err]) => (i > maxTries ? throwError(err) : of(i))),
map(i => i * i), // 1 * 1, 2 * 2...
mergeMap(v => {
return timer(v * delay);
}),
);
}),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment