Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): adding custom rxjs operator retryWithBackoff
- Loading branch information
Showing
4 changed files
with
43 additions
and
5 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { Observable, of, throwError } from 'rxjs'; | ||
import { delay, mergeMap, retryWhen } from 'rxjs/operators'; | ||
|
||
const getErrorMessage = (maxRetry: number) => | ||
`Tried to load Resource over XHR for ${maxRetry} times without success. Giving up.`; | ||
|
||
const DEFAULT_MAX_RETRIES = 5; | ||
const DEFAULT_BACKOFF = 1000; | ||
|
||
export function retryWithBackoff<T>( | ||
delayMs: number, | ||
maxRetry = DEFAULT_BACKOFF, | ||
backoffMs = DEFAULT_BACKOFF, | ||
): (src$: Observable<T>) => Observable<T> { | ||
let retries = maxRetry; | ||
|
||
return (src$: Observable<T>): Observable<T> => | ||
src$.pipe( | ||
retryWhen((errors: Observable<T>) => | ||
errors.pipe( | ||
mergeMap(error => { | ||
if (retries-- > 0) { | ||
const backoffTime = delayMs + (maxRetry - retries) * backoffMs; | ||
return of(error).pipe(delay(backoffTime)); | ||
} | ||
return throwError(getErrorMessage(maxRetry)); | ||
}), | ||
), | ||
), | ||
); | ||
} |
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