Debian Codegraph @

node/rxjs/src/internal/operators/retry.ts

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