Created
November 16, 2022 16:30
-
-
Save lydemann/5ce2e8a5d77918aeed292ce8f3799661 to your computer and use it in GitHub Desktop.
exponential-backoff-retry.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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