5fe51aafc73a15e4def055e21af2adb9316ce56b494eb6664e8d12db0df1dda373c962f0904e7776aa785f4763479147b21982ddccb01fc79d269c946cc0f2 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import { MonoTypeOperatorFunction, ObservableInput } from '../types';
  2. import { operate } from '../util/lift';
  3. import { Subscription } from '../Subscription';
  4. import { createOperatorSubscriber } from './OperatorSubscriber';
  5. import { identity } from '../util/identity';
  6. import { timer } from '../observable/timer';
  7. import { innerFrom } from '../observable/innerFrom';
  8. /**
  9. * The {@link retry} operator configuration object. `retry` either accepts a `number`
  10. * or an object described by this interface.
  11. */
  12. export interface RetryConfig {
  13. /**
  14. * The maximum number of times to retry. If `count` is omitted, `retry` will try to
  15. * resubscribe on errors infinite number of times.
  16. */
  17. count?: number;
  18. /**
  19. * The number of milliseconds to delay before retrying, OR a function to
  20. * return a notifier for delaying. If a function is given, that function should
  21. * return a notifier that, when it emits will retry the source. If the notifier
  22. * completes _without_ emitting, the resulting observable will complete without error,
  23. * if the notifier errors, the error will be pushed to the result.
  24. */
  25. delay?: number | ((error: any, retryCount: number) => ObservableInput<any>);
  26. /**
  27. * Whether or not to reset the retry counter when the retried subscription
  28. * emits its first value.
  29. */
  30. resetOnSuccess?: boolean;
  31. }
  32. export function retry<T>(count?: number): MonoTypeOperatorFunction<T>;
  33. export function retry<T>(config: RetryConfig): MonoTypeOperatorFunction<T>;
  34. /**
  35. * Returns an Observable that mirrors the source Observable with the exception of an `error`.
  36. *
  37. * If the source Observable calls `error`, this method will resubscribe to the source Observable for a maximum of
  38. * `count` resubscriptions rather than propagating the `error` call.
  39. *
  40. * ![](retry.png)
  41. *
  42. * The number of retries is determined by the `count` parameter. It can be set either by passing a number to
  43. * `retry` function or by setting `count` property when `retry` is configured using {@link RetryConfig}. If
  44. * `count` is omitted, `retry` will try to resubscribe on errors infinite number of times.
  45. *
  46. * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those
  47. * emitted during failed subscriptions. For example, if an Observable fails at first but emits `[1, 2]` then
  48. * succeeds the second time and emits: `[1, 2, 3, 4, 5, complete]` then the complete stream of emissions and
  49. * notifications would be: `[1, 2, 1, 2, 3, 4, 5, complete]`.
  50. *
  51. * ## Example
  52. *
  53. * ```ts
  54. * import { interval, mergeMap, throwError, of, retry } from 'rxjs';
  55. *
  56. * const source = interval(1000);
  57. * const result = source.pipe(
  58. * mergeMap(val => val > 5 ? throwError(() => 'Error!') : of(val)),
  59. * retry(2) // retry 2 times on error
  60. * );
  61. *
  62. * result.subscribe({
  63. * next: value => console.log(value),
  64. * error: err => console.log(`${ err }: Retried 2 times then quit!`)
  65. * });
  66. *
  67. * // Output:
  68. * // 0..1..2..3..4..5..
  69. * // 0..1..2..3..4..5..
  70. * // 0..1..2..3..4..5..
  71. * // 'Error!: Retried 2 times then quit!'
  72. * ```
  73. *
  74. * @see {@link retryWhen}
  75. *
  76. * @param configOrCount Either number of retry attempts before failing or a
  77. * {@link RetryConfig} object.
  78. * @return A function that returns an Observable that will resubscribe to the
  79. * source stream when the source stream errors, at most `count` times.
  80. */
  81. export function retry<T>(configOrCount: number | RetryConfig = Infinity): MonoTypeOperatorFunction<T> {
  82. let config: RetryConfig;
  83. if (configOrCount && typeof configOrCount === 'object') {
  84. config = configOrCount;
  85. } else {
  86. config = {
  87. count: configOrCount as number,
  88. };
  89. }
  90. const { count = Infinity, delay, resetOnSuccess: resetOnSuccess = false } = config;
  91. return count <= 0
  92. ? identity
  93. : operate((source, subscriber) => {
  94. let soFar = 0;
  95. let innerSub: Subscription | null;
  96. const subscribeForRetry = () => {
  97. let syncUnsub = false;
  98. innerSub = source.subscribe(
  99. createOperatorSubscriber(
  100. subscriber,
  101. (value) => {
  102. // If we're resetting on success
  103. if (resetOnSuccess) {
  104. soFar = 0;
  105. }
  106. subscriber.next(value);
  107. },
  108. // Completions are passed through to consumer.
  109. undefined,
  110. (err) => {
  111. if (soFar++ < count) {
  112. // We are still under our retry count
  113. const resub = () => {
  114. if (innerSub) {
  115. innerSub.unsubscribe();
  116. innerSub = null;
  117. subscribeForRetry();
  118. } else {
  119. syncUnsub = true;
  120. }
  121. };
  122. if (delay != null) {
  123. // The user specified a retry delay.
  124. // They gave us a number, use a timer, otherwise, it's a function,
  125. // and we're going to call it to get a notifier.
  126. const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));
  127. const notifierSubscriber = createOperatorSubscriber(
  128. subscriber,
  129. () => {
  130. // After we get the first notification, we
  131. // unsubscribe from the notifier, because we don't want anymore
  132. // and we resubscribe to the source.
  133. notifierSubscriber.unsubscribe();
  134. resub();
  135. },
  136. () => {
  137. // The notifier completed without emitting.
  138. // The author is telling us they want to complete.
  139. subscriber.complete();
  140. }
  141. );
  142. notifier.subscribe(notifierSubscriber);
  143. } else {
  144. // There was no notifier given. Just resub immediately.
  145. resub();
  146. }
  147. } else {
  148. // We're past our maximum number of retries.
  149. // Just send along the error.
  150. subscriber.error(err);
  151. }
  152. }
  153. )
  154. );
  155. if (syncUnsub) {
  156. innerSub.unsubscribe();
  157. innerSub = null;
  158. subscribeForRetry();
  159. }
  160. };
  161. subscribeForRetry();
  162. });
  163. }