retry.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Subscriber } from '../Subscriber';
  2. /**
  3. * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
  4. * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
  5. * as a number parameter) rather than propagating the `error` call.
  6. *
  7. * <img src="./img/retry.png" width="100%">
  8. *
  9. * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
  10. * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
  11. * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
  12. * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
  13. * @param {number} count - Number of retry attempts before failing.
  14. * @return {Observable} The source Observable modified with the retry logic.
  15. * @method retry
  16. * @owner Observable
  17. */
  18. export function retry(count = -1) {
  19. return (source) => source.lift(new RetryOperator(count, source));
  20. }
  21. class RetryOperator {
  22. constructor(count, source) {
  23. this.count = count;
  24. this.source = source;
  25. }
  26. call(subscriber, source) {
  27. return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
  28. }
  29. }
  30. /**
  31. * We need this JSDoc comment for affecting ESDoc.
  32. * @ignore
  33. * @extends {Ignored}
  34. */
  35. class RetrySubscriber extends Subscriber {
  36. constructor(destination, count, source) {
  37. super(destination);
  38. this.count = count;
  39. this.source = source;
  40. }
  41. error(err) {
  42. if (!this.isStopped) {
  43. const { source, count } = this;
  44. if (count === 0) {
  45. return super.error(err);
  46. }
  47. else if (count > -1) {
  48. this.count = count - 1;
  49. }
  50. source.subscribe(this._unsubscribeAndRecycle());
  51. }
  52. }
  53. }
  54. //# sourceMappingURL=retry.js.map