-
Notifications
You must be signed in to change notification settings - Fork 3k
/
share.ts
233 lines (217 loc) · 9 KB
/
share.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { Observable } from '../Observable';
import { from } from '../observable/from';
import { take } from '../operators/take';
import { Subject } from '../Subject';
import { SafeSubscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { MonoTypeOperatorFunction, SubjectLike } from '../types';
import { operate } from '../util/lift';
export interface ShareConfig<T> {
/**
* The factory used to create the subject that will connect the source observable to
* multicast consumers.
*/
connector?: () => SubjectLike<T>;
/**
* If true, the resulting observable will reset internal state on error from source and return to a "cold" state. This
* allows the resulting observable to be "retried" in the event of an error.
* If false, when an error comes from the source it will push the error into the connecting subject, and the subject
* will remain the connecting subject, meaning the resulting observable will not go "cold" again, and subsequent retries
* or resubscriptions will resubscribe to that same subject. In all cases, RxJS subjects will emit the same error again, however
* {@link ReplaySubject} will also push its buffered values before pushing the error.
* It is also possible to pass a notifier factory returning an observable instead which grants more fine-grained
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.
*/
resetOnError?: boolean | ((error: any) => Observable<any>);
/**
* If true, the resulting observable will reset internal state on completion from source and return to a "cold" state. This
* allows the resulting observable to be "repeated" after it is done.
* If false, when the source completes, it will push the completion through the connecting subject, and the subject
* will remain the connecting subject, meaning the resulting observable will not go "cold" again, and subsequent repeats
* or resubscriptions will resubscribe to that same subject.
* It is also possible to pass a notifier factory returning an observable instead which grants more fine-grained
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.
*/
resetOnComplete?: boolean | (() => Observable<any>);
/**
* If true, when the number of subscribers to the resulting observable reaches zero due to those subscribers unsubscribing, the
* internal state will be reset and the resulting observable will return to a "cold" state. This means that the next
* time the resulting observable is subscribed to, a new subject will be created and the source will be subscribed to
* again.
* If false, when the number of subscribers to the resulting observable reaches zero due to unsubscription, the subject
* will remain connected to the source, and new subscriptions to the result will be connected through that same subject.
* It is also possible to pass a notifier factory returning an observable instead which grants more fine-grained
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.
*/
resetOnRefCountZero?: boolean | (() => Observable<any>);
}
export function share<T>(): MonoTypeOperatorFunction<T>;
export function share<T>(options: ShareConfig<T>): MonoTypeOperatorFunction<T>;
/**
* Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
* Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
* unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
* This is an alias for `multicast(() => new Subject()), refCount()`.
*
* ![](share.png)
*
* ## Example
* Generate new multicast Observable from the source Observable value
* ```ts
* import { interval } from 'rxjs';
* import { share, map } from 'rxjs/operators';
*
* const source = interval(1000)
* .pipe(
* map((x: number) => {
* console.log('Processing: ', x);
* return x*x;
* }),
* share()
* );
*
* source.subscribe(x => console.log('subscription 1: ', x));
* source.subscribe(x => console.log('subscription 1: ', x));
*
* // Logs:
* // Processing: 0
* // subscription 1: 0
* // subscription 1: 0
* // Processing: 1
* // subscription 1: 1
* // subscription 1: 1
* // Processing: 2
* // subscription 1: 4
* // subscription 1: 4
* // Processing: 3
* // subscription 1: 9
* // subscription 1: 9
* // ... and so on
* ```
*
* ## Example with notifier factory: Delayed reset
* ```ts
* import { interval } from 'rxjs';
* import { share, take, timer } from 'rxjs/operators';
*
* const source = interval(1000).pipe(take(3), share({ resetOnRefCountZero: () => timer(1000) }));
*
* const subscriptionOne = source.subscribe(x => console.log('subscription 1: ', x));
* setTimeout(() => subscriptionOne.unsubscribe(), 1300);
*
* setTimeout(() => source.subscribe(x => console.log('subscription 2: ', x)), 1700);
*
* setTimeout(() => source.subscribe(x => console.log('subscription 3: ', x)), 5000);
*
* // Logs:
* // subscription 1: 0
* // (subscription 1 unsubscribes here)
* // (subscription 2 subscribes here ~400ms later, source was not reset)
* // subscription 2: 1
* // subscription 2: 2
* // (subscription 2 unsubscribes here)
* // (subscription 3 subscribes here ~2000ms later, source did reset before)
* // subscription 3: 0
* // subscription 3: 1
* // subscription 3: 2
* ```
*
* @see {@link api/index/function/interval}
* @see {@link map}
*
* @return A function that returns an Observable that mirrors the source.
*/
export function share<T>(options: ShareConfig<T> = {}): MonoTypeOperatorFunction<T> {
const { connector = () => new Subject<T>(), resetOnError = true, resetOnComplete = true, resetOnRefCountZero = true } = options;
let connection: SafeSubscriber<T> | null = null;
let resetConnection: Subscription | null = null;
let subject: SubjectLike<T> | null = null;
let refCount = 0;
let hasCompleted = false;
let hasErrored = false;
const cancelReset = () => {
resetConnection?.unsubscribe();
resetConnection = null;
};
// Used to reset the internal state to a "cold"
// state, as though it had never been subscribed to.
const reset = () => {
cancelReset();
connection = subject = null;
hasCompleted = hasErrored = false;
};
const resetAndUnsubscribe = () => {
// We need to capture the connection before
// we reset (if we need to reset).
const conn = connection;
reset();
conn?.unsubscribe();
};
return operate((source, subscriber) => {
refCount++;
if (!hasErrored && !hasCompleted) {
cancelReset();
}
// Create the subject if we don't have one yet.
subject = subject ?? connector();
// The following line adds the subscription to the subscriber passed.
// Basically, `subscriber === subject.subscribe(subscriber)` is `true`.
subject.subscribe(subscriber);
if (!connection) {
// We need to create a subscriber here - rather than pass an observer and
// assign the returned subscription to connection - because it's possible
// for reentrant subscriptions to the shared observable to occur and in
// those situations we want connection to be already-assigned so that we
// don't create another connection to the source.
connection = new SafeSubscriber({
next: (value: T) => subject!.next(value),
error: (err: any) => {
hasErrored = true;
// We need to capture the subject before
// we reset (if we need to reset).
const dest = subject!;
cancelReset();
resetConnection = handleReset(reset, resetOnError, err);
dest.error(err);
},
complete: () => {
hasCompleted = true;
// We need to capture the subject before
// we reset (if we need to reset).
const dest = subject!;
cancelReset();
resetConnection = handleReset(reset, resetOnComplete);
dest.complete();
},
});
from(source).subscribe(connection);
}
// This is also added to `subscriber`, technically.
return () => {
refCount--;
// If we're resetting on refCount === 0, and it's 0, we only want to do
// that on "unsubscribe", really. Resetting on error or completion is a different
// configuration.
if (refCount === 0 && !hasErrored && !hasCompleted) {
cancelReset(); // paranoia, there should never be a resetConnection, if we reached this point
resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
}
};
});
}
function handleReset<T extends unknown[] = never[]>(
fn: () => void,
on: boolean | ((...args: T) => Observable<any>),
...args: T
): Subscription | null {
if (on === true) {
fn();
return null;
}
if (on === false) {
return null;
}
return on(...args)
.pipe(take(1))
.subscribe(() => fn());
}