Last active
November 23, 2021 15:32
-
-
Save tanem/011a950b93a89e43cfc335f617dbb230 to your computer and use it in GitHub Desktop.
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
// 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