Skip to content

Instantly share code, notes, and snippets.

@lydemann
Created November 16, 2022 16:30
Show Gist options
  • Save lydemann/5ce2e8a5d77918aeed292ce8f3799661 to your computer and use it in GitHub Desktop.
Save lydemann/5ce2e8a5d77918aeed292ce8f3799661 to your computer and use it in GitHub Desktop.
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