Skip to content

Instantly share code, notes, and snippets.

@ValentinFunk
Created September 10, 2017 10:57
Show Gist options
  • Save ValentinFunk/f0868eb8482113564880cdc1211f6cab to your computer and use it in GitHub Desktop.
Save ValentinFunk/f0868eb8482113564880cdc1211f6cab to your computer and use it in GitHub Desktop.
Retry HTTP in RXJs
function retryHttp<T>(retryCount: number, shouldRetry: (error: { code: number }) => boolean) {
return (request$: Observable<T>): Observable<T> => request$.retryWhen(
errors$ => errors$.flatMap(error => {
if (shouldRetry(error)) {
return Observable.of(true).delay(1000);
}
return Observable.throw({ error: 'Error cannot be retried', originalError: error });
}).take(5)
.concat(Observable.throw(`Request failed after ${retryCount} retries.`))
);
}
// Eg:
$http.get('https://google.com').let(retryHttp(10, error => error.code === 500));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment