Last active
          August 24, 2023 11:38 
        
      - 
      
- 
        Save magnobiet/abdf5aef42d3b664c59bbd0cb45bc3bd to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or 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 { iif, Observable, throwError, timer } from 'rxjs'; | |
| import { mergeMap, retryWhen, take } from 'rxjs/operators'; | |
| export function retryOnError<T>( | |
| maximumRetries = 3, | |
| delayInMilliseconds = 1000, | |
| ): (source$: Observable<T>) => Observable<T> { | |
| return (source$) => { | |
| return source$.pipe( | |
| retryWhen((errors) => { | |
| return errors.pipe( | |
| mergeMap((error, retries) => { | |
| return iif( | |
| () => retries < maximumRetries, | |
| timer(delayInMilliseconds), | |
| throwError(error), | |
| ); | |
| }), | |
| ); | |
| }), | |
| take(1), | |
| ); | |
| }; | |
| } | |
| // Usage | |
| @Injectable({ providedIn: 'root' }) | |
| export class AwesomeService { | |
| constructor(private readonly http: HttpClient) {} | |
| public retrieveAwesomeThing(): Observable<Array<Awesome>> { | |
| return this.http.get<Array<Awesome>>(`/awesome-endpoint`).pipe(retryOnError()); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment