retry

signature: retry(number: number): Observable

Retry an observable sequence a specific number of times should an error occur.

retry - 图1

Examples

Example 1: Retry 2 times on error

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { of } from 'rxjs/observable/of';
  3. import { _throw } from 'rxjs/observable/throw';
  4. import { mergeMap, retry } 'rxjs/operators';
  5. //emit value every 1s
  6. const source = interval(1000);
  7. const example = source.pipe(
  8. mergeMap(val => {
  9. //throw error for demonstration
  10. if (val > 5) {
  11. return _throw('Error!');
  12. }
  13. return of(val);
  14. }),
  15. //retry 2 times on error
  16. retry(2)
  17. );
  18. /*
  19. output:
  20. 0..1..2..3..4..5..
  21. 0..1..2..3..4..5..
  22. 0..1..2..3..4..5..
  23. "Error!: Retried 2 times then quit!"
  24. */
  25. const subscribe = example.subscribe({
  26. next: val => console.log(val),
  27. error: val => console.log(`${val}: Retried 2 times then quit!`)
  28. });

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/retry.ts