Debian Codegraph @

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

raw
1 import { Subscription } from '../Subscription';
2 import { EMPTY } from '../observable/empty';
3 import { operate } from '../util/lift';
4 import { MonoTypeOperatorFunction, ObservableInput } from '../types';
5 import { createOperatorSubscriber } from './OperatorSubscriber';
6 import { innerFrom } from '../observable/innerFrom';
7 import { timer } from '../observable/timer';
8
9 export interface RepeatConfig {
10 /**
11 * The number of times to repeat the source. Defaults to `Infinity`.
12 */
13 count?: number;
14
15 /**
16 * If a `number`, will delay the repeat of the source by that number of milliseconds.
17 * If a function, it will provide the number of times the source has been subscribed to,
18 * and the return value should be a valid observable input that will notify when the source
19 * should be repeated. If the notifier observable is empty, the result will complete.
20 */
21 delay?: number | ((count: number) => ObservableInput<any>);
22 }
23
24 /**
25 * Returns an Observable that will resubscribe to the source stream when the source stream completes.
26 *
27 * <span class="informal">Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.</span>
28 *
29 * ![](repeat.png)
30 *
31 * Repeat will output values from a source until the source completes, then it will resubscribe to the
32 * source a specified number of times, with a specified delay. Repeat can be particularly useful in
33 * combination with closing operators like {@link take}, {@link takeUntil}, {@link first}, or {@link takeWhile},
34 * as it can be used to restart a source again from scratch.
35 *
36 * Repeat is very similar to {@link retry}, where {@link retry} will resubscribe to the source in the error case, but
37 * `repeat` will resubscribe if the source completes.
38 *
39 * Note that `repeat` will _not_ catch errors. Use {@link retry} for that.
40 *
41 * - `repeat(0)` returns an empty observable
42 * - `repeat()` will repeat forever
43 * - `repeat({ delay: 200 })` will repeat forever, with a delay of 200ms between repetitions.
44 * - `repeat({ count: 2, delay: 400 })` will repeat twice, with a delay of 400ms between repetitions.
45 * - `repeat({ delay: (count) => timer(count * 1000) })` will repeat forever, but will have a delay that grows by one second for each repetition.
46 *
47 * ## Example
48 *
49 * Repeat a message stream
50 *
51 * ```ts
52 * import { of, repeat } from 'rxjs';
53 *
54 * const source = of('Repeat message');
55 * const result = source.pipe(repeat(3));
56 *
57 * result.subscribe(x => console.log(x));
58 *
59 * // Results
60 * // 'Repeat message'
61 * // 'Repeat message'
62 * // 'Repeat message'
63 * ```
64 *
65 * Repeat 3 values, 2 times
66 *
67 * ```ts
68 * import { interval, take, repeat } from 'rxjs';
69 *
70 * const source = interval(1000);
71 * const result = source.pipe(take(3), repeat(2));
72 *
73 * result.subscribe(x => console.log(x));
74 *
75 * // Results every second
76 * // 0
77 * // 1
78 * // 2
79 * // 0
80 * // 1
81 * // 2
82 * ```
83 *
84 * Defining two complex repeats with delays on the same source.
85 * Note that the second repeat cannot be called until the first
86 * repeat as exhausted it's count.
87 *
88 * ```ts
89 * import { defer, of, repeat } from 'rxjs';
90 *
91 * const source = defer(() => {
92 * return of(`Hello, it is ${new Date()}`)
93 * });
94 *
95 * source.pipe(
96 * // Repeat 3 times with a delay of 1 second between repetitions
97 * repeat({
98 * count: 3,
99 * delay: 1000,
100 * }),
101 *
102 * // *Then* repeat forever, but with an exponential step-back
103 * // maxing out at 1 minute.
104 * repeat({
105 * delay: (count) => timer(Math.min(60000, 2 ^ count * 1000))
106 * })
107 * )
108 * ```
109 *
110 * @see {@link repeatWhen}
111 * @see {@link retry}
112 *
113 * @param countOrConfig Either the number of times the source Observable items are repeated
114 * (a count of 0 will yield an empty Observable) or a {@link RepeatConfig} object.
115 */
116 export function repeat<T>(countOrConfig?: number | RepeatConfig): MonoTypeOperatorFunction<T> {
117 let count = Infinity;
118 let delay: RepeatConfig['delay'];
119
120 if (countOrConfig != null) {
121 if (typeof countOrConfig === 'object') {
122 ({ count = Infinity, delay } = countOrConfig);
123 } else {
124 count = countOrConfig;
125 }
126 }
127
128 return count <= 0
129 ? () => EMPTY
130 : operate((source, subscriber) => {
131 let soFar = 0;
132 let sourceSub: Subscription | null;
133
134 const resubscribe = () => {
135 sourceSub?.unsubscribe();
136 sourceSub = null;
137 if (delay != null) {
138 const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(soFar));
139 const notifierSubscriber = createOperatorSubscriber(subscriber, () => {
140 notifierSubscriber.unsubscribe();
141 subscribeToSource();
142 });
143 notifier.subscribe(notifierSubscriber);
144 } else {
145 subscribeToSource();
146 }
147 };
148
149 const subscribeToSource = () => {
150 let syncUnsub = false;
151 sourceSub = source.subscribe(
152 createOperatorSubscriber(subscriber, undefined, () => {
153 if (++soFar < count) {
154 if (sourceSub) {
155 resubscribe();
156 } else {
157 syncUnsub = true;
158 }
159 } else {
160 subscriber.complete();
161 }
162 })
163 );
164
165 if (syncUnsub) {
166 resubscribe();
167 }
168 };
169
170 subscribeToSource();
171 });
172 }