Last active
May 23, 2018 03:23
-
-
Save alex-okrushko/14d41c0f06b9d0191d6c0d7d6143da95 to your computer and use it in GitHub Desktop.
Exponential backoff retry - fake service
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 { Injectable } from '@angular/core'; | |
import { of, throwError, defer } from 'rxjs'; | |
export interface HttpError { | |
error: string, | |
status: string, | |
} | |
const ERROR_404: HttpError = { error: 'No need to try anymore', status: '404' }; | |
const ERROR_503: HttpError = { error: 'Try again?', status: '503' }; | |
@Injectable() | |
export class BackendService { | |
retries = 0; | |
/** | |
* Fake backend responses. | |
* Fails with 503 until 10-th retry | |
* Fails with 404 on 5-th retry | |
* Succeeds on 10+ | |
*/ | |
callBackend() { | |
this.retries++; | |
const result$ = (this.retries >= 10) | |
? of({ data: 'Success!', status: '200' }) | |
: (this.retries === 5) | |
? throwError(ERROR_404) | |
: throwError(ERROR_503); | |
return defer(() => result$); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment