Skip to content

Instantly share code, notes, and snippets.

@tanem
Last active November 23, 2021 15:32
Show Gist options
  • Save tanem/011a950b93a89e43cfc335f617dbb230 to your computer and use it in GitHub Desktop.
Save tanem/011a950b93a89e43cfc335f617dbb230 to your computer and use it in GitHub Desktop.
// Credit: https://www.learnrxjs.io/operators/error_handling/retrywhen.html.
import { throwError, timer } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { finalize, mergeMap, retryWhen } from 'rxjs/operators';
const genericRetryStrategy = ({
maxRetryAttempts = 3,
scalingDuration = 5000
} = {}) => errors =>
errors.pipe(
mergeMap((error, index) => {
const retryAttempt = index + 1;
if (retryAttempt > maxRetryAttempts) {
return throwError(error);
}
console.log(
`Attempt ${retryAttempt}: Retrying in ${retryAttempt *
scalingDuration}ms`
);
return timer(retryAttempt * scalingDuration);
}),
finalize(() => console.log('We are done!'))
);
const req = ajax
.getJSON('https://jsonplaceholder.typicode.com/todos/1')
.pipe(retryWhen(genericRetryStrategy()));
req.subscribe({
next(x) {
console.log('next', x);
},
error(error) {
console.error('error', error);
},
complete() {
console.log('complete');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment