Debian Codegraph @

node/rxjs/src/internal/Observable.ts

raw
1 import { Operator } from './Operator';
2 import { SafeSubscriber, Subscriber } from './Subscriber';
3 import { isSubscription, Subscription } from './Subscription';
4 import { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';
5 import { observable as Symbol_observable } from './symbol/observable';
6 import { pipeFromArray } from './util/pipe';
7 import { config } from './config';
8 import { isFunction } from './util/isFunction';
9 import { errorContext } from './util/errorContext';
10
11 /**
12 * A representation of any set of values over any amount of time. This is the most basic building block
13 * of RxJS.
14 */
15 export class Observable<T> implements Subscribable<T> {
16 /**
17 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
18 */
19 source: Observable<any> | undefined;
20
21 /**
22 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
23 */
24 operator: Operator<any, T> | undefined;
25
26 /**
27 * @param subscribe The function that is called when the Observable is
28 * initially subscribed to. This function is given a Subscriber, to which new values
29 * can be `next`ed, or an `error` method can be called to raise an error, or
30 * `complete` can be called to notify of a successful completion.
31 */
32 constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
33 if (subscribe) {
34 this._subscribe = subscribe;
35 }
36 }
37
38 // HACK: Since TypeScript inherits static properties too, we have to
39 // fight against TypeScript here so Subject can have a different static create signature
40 /**
41 * Creates a new Observable by calling the Observable constructor
42 * @param subscribe the subscriber function to be passed to the Observable constructor
43 * @return A new observable.
44 * @deprecated Use `new Observable()` instead. Will be removed in v8.
45 */
46 static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
47 return new Observable<T>(subscribe);
48 };
49
50 /**
51 * Creates a new Observable, with this Observable instance as the source, and the passed
52 * operator defined as the new observable's operator.
53 * @param operator the operator defining the operation to take on the observable
54 * @return A new observable with the Operator applied.
55 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
56 * If you have implemented an operator using `lift`, it is recommended that you create an
57 * operator by simply returning `new Observable()` directly. See "Creating new operators from
58 * scratch" section here: https://rxjs.dev/guide/operators
59 */
60 lift<R>(operator?: Operator<T, R>): Observable<R> {
61 const observable = new Observable<R>();
62 observable.source = this;
63 observable.operator = operator;
64 return observable;
65 }
66
67 subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;
68 /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */
69 subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;
70 /**
71 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
72 *
73 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
74 *
75 * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
76 * might be for example a function that you passed to Observable's constructor, but most of the time it is
77 * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
78 * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
79 * the thought.
80 *
81 * Apart from starting the execution of an Observable, this method allows you to listen for values
82 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
83 * of the following ways.
84 *
85 * The first way is creating an object that implements {@link Observer} interface. It should have methods
86 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
87 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do
88 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
89 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
90 * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,
91 * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,
92 * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or
93 * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide
94 * an `error` method to avoid missing thrown errors.
95 *
96 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
97 * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
98 * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,
99 * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,
100 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
101 * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.
102 *
103 * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events
104 * and you also handled emissions internally by using operators (e.g. using `tap`).
105 *
106 * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
107 * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
108 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
109 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
110 *
111 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
112 * It is an Observable itself that decides when these functions will be called. For example {@link of}
113 * by default emits all its values synchronously. Always check documentation for how given Observable
114 * will behave when subscribed and if its default behavior can be modified with a `scheduler`.
115 *
116 * #### Examples
117 *
118 * Subscribe with an {@link guide/observer Observer}
119 *
120 * ```ts
121 * import { of } from 'rxjs';
122 *
123 * const sumObserver = {
124 * sum: 0,
125 * next(value) {
126 * console.log('Adding: ' + value);
127 * this.sum = this.sum + value;
128 * },
129 * error() {
130 * // We actually could just remove this method,
131 * // since we do not really care about errors right now.
132 * },
133 * complete() {
134 * console.log('Sum equals: ' + this.sum);
135 * }
136 * };
137 *
138 * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
139 * .subscribe(sumObserver);
140 *
141 * // Logs:
142 * // 'Adding: 1'
143 * // 'Adding: 2'
144 * // 'Adding: 3'
145 * // 'Sum equals: 6'
146 * ```
147 *
148 * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})
149 *
150 * ```ts
151 * import { of } from 'rxjs'
152 *
153 * let sum = 0;
154 *
155 * of(1, 2, 3).subscribe(
156 * value => {
157 * console.log('Adding: ' + value);
158 * sum = sum + value;
159 * },
160 * undefined,
161 * () => console.log('Sum equals: ' + sum)
162 * );
163 *
164 * // Logs:
165 * // 'Adding: 1'
166 * // 'Adding: 2'
167 * // 'Adding: 3'
168 * // 'Sum equals: 6'
169 * ```
170 *
171 * Cancel a subscription
172 *
173 * ```ts
174 * import { interval } from 'rxjs';
175 *
176 * const subscription = interval(1000).subscribe({
177 * next(num) {
178 * console.log(num)
179 * },
180 * complete() {
181 * // Will not be called, even when cancelling subscription.
182 * console.log('completed!');
183 * }
184 * });
185 *
186 * setTimeout(() => {
187 * subscription.unsubscribe();
188 * console.log('unsubscribed!');
189 * }, 2500);
190 *
191 * // Logs:
192 * // 0 after 1s
193 * // 1 after 2s
194 * // 'unsubscribed!' after 2.5s
195 * ```
196 *
197 * @param observerOrNext Either an {@link Observer} with some or all callback methods,
198 * or the `next` handler that is called for each value emitted from the subscribed Observable.
199 * @param error A handler for a terminal event resulting from an error. If no error handler is provided,
200 * the error will be thrown asynchronously as unhandled.
201 * @param complete A handler for a terminal event resulting from successful completion.
202 * @return A subscription reference to the registered handlers.
203 */
204 subscribe(
205 observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,
206 error?: ((error: any) => void) | null,
207 complete?: (() => void) | null
208 ): Subscription {
209 const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
210
211 errorContext(() => {
212 const { operator, source } = this;
213 subscriber.add(
214 operator
215 ? // We're dealing with a subscription in the
216 // operator chain to one of our lifted operators.
217 operator.call(subscriber, source)
218 : source
219 ? // If `source` has a value, but `operator` does not, something that
220 // had intimate knowledge of our API, like our `Subject`, must have
221 // set it. We're going to just call `_subscribe` directly.
222 this._subscribe(subscriber)
223 : // In all other cases, we're likely wrapping a user-provided initializer
224 // function, so we need to catch errors and handle them appropriately.
225 this._trySubscribe(subscriber)
226 );
227 });
228
229 return subscriber;
230 }
231
232 /** @internal */
233 protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {
234 try {
235 return this._subscribe(sink);
236 } catch (err) {
237 // We don't need to return anything in this case,
238 // because it's just going to try to `add()` to a subscription
239 // above.
240 sink.error(err);
241 }
242 }
243
244 /**
245 * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with
246 * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.
247 *
248 * **WARNING**: Only use this with observables you *know* will complete. If the source
249 * observable does not complete, you will end up with a promise that is hung up, and
250 * potentially all of the state of an async function hanging out in memory. To avoid
251 * this situation, look into adding something like {@link timeout}, {@link take},
252 * {@link takeWhile}, or {@link takeUntil} amongst others.
253 *
254 * #### Example
255 *
256 * ```ts
257 * import { interval, take } from 'rxjs';
258 *
259 * const source$ = interval(1000).pipe(take(4));
260 *
261 * async function getTotal() {
262 * let total = 0;
263 *
264 * await source$.forEach(value => {
265 * total += value;
266 * console.log('observable -> ' + value);
267 * });
268 *
269 * return total;
270 * }
271 *
272 * getTotal().then(
273 * total => console.log('Total: ' + total)
274 * );
275 *
276 * // Expected:
277 * // 'observable -> 0'
278 * // 'observable -> 1'
279 * // 'observable -> 2'
280 * // 'observable -> 3'
281 * // 'Total: 6'
282 * ```
283 *
284 * @param next A handler for each value emitted by the observable.
285 * @return A promise that either resolves on observable completion or
286 * rejects with the handled error.
287 */
288 forEach(next: (value: T) => void): Promise<void>;
289
290 /**
291 * @param next a handler for each value emitted by the observable
292 * @param promiseCtor a constructor function used to instantiate the Promise
293 * @return a promise that either resolves on observable completion or
294 * rejects with the handled error
295 * @deprecated Passing a Promise constructor will no longer be available
296 * in upcoming versions of RxJS. This is because it adds weight to the library, for very
297 * little benefit. If you need this functionality, it is recommended that you either
298 * polyfill Promise, or you create an adapter to convert the returned native promise
299 * to whatever promise implementation you wanted. Will be removed in v8.
300 */
301 forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;
302
303 forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
304 promiseCtor = getPromiseCtor(promiseCtor);
305
306 return new promiseCtor<void>((resolve, reject) => {
307 const subscriber = new SafeSubscriber<T>({
308 next: (value) => {
309 try {
310 next(value);
311 } catch (err) {
312 reject(err);
313 subscriber.unsubscribe();
314 }
315 },
316 error: reject,
317 complete: resolve,
318 });
319 this.subscribe(subscriber);
320 }) as Promise<void>;
321 }
322
323 /** @internal */
324 protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {
325 return this.source?.subscribe(subscriber);
326 }
327
328 /**
329 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
330 * @return This instance of the observable.
331 */
332 [Symbol_observable]() {
333 return this;
334 }
335
336 /* tslint:disable:max-line-length */
337 pipe(): Observable<T>;
338 pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
339 pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
340 pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
341 pipe<A, B, C, D>(
342 op1: OperatorFunction<T, A>,
343 op2: OperatorFunction<A, B>,
344 op3: OperatorFunction<B, C>,
345 op4: OperatorFunction<C, D>
346 ): Observable<D>;
347 pipe<A, B, C, D, E>(
348 op1: OperatorFunction<T, A>,
349 op2: OperatorFunction<A, B>,
350 op3: OperatorFunction<B, C>,
351 op4: OperatorFunction<C, D>,
352 op5: OperatorFunction<D, E>
353 ): Observable<E>;
354 pipe<A, B, C, D, E, F>(
355 op1: OperatorFunction<T, A>,
356 op2: OperatorFunction<A, B>,
357 op3: OperatorFunction<B, C>,
358 op4: OperatorFunction<C, D>,
359 op5: OperatorFunction<D, E>,
360 op6: OperatorFunction<E, F>
361 ): Observable<F>;
362 pipe<A, B, C, D, E, F, G>(
363 op1: OperatorFunction<T, A>,
364 op2: OperatorFunction<A, B>,
365 op3: OperatorFunction<B, C>,
366 op4: OperatorFunction<C, D>,
367 op5: OperatorFunction<D, E>,
368 op6: OperatorFunction<E, F>,
369 op7: OperatorFunction<F, G>
370 ): Observable<G>;
371 pipe<A, B, C, D, E, F, G, H>(
372 op1: OperatorFunction<T, A>,
373 op2: OperatorFunction<A, B>,
374 op3: OperatorFunction<B, C>,
375 op4: OperatorFunction<C, D>,
376 op5: OperatorFunction<D, E>,
377 op6: OperatorFunction<E, F>,
378 op7: OperatorFunction<F, G>,
379 op8: OperatorFunction<G, H>
380 ): Observable<H>;
381 pipe<A, B, C, D, E, F, G, H, I>(
382 op1: OperatorFunction<T, A>,
383 op2: OperatorFunction<A, B>,
384 op3: OperatorFunction<B, C>,
385 op4: OperatorFunction<C, D>,
386 op5: OperatorFunction<D, E>,
387 op6: OperatorFunction<E, F>,
388 op7: OperatorFunction<F, G>,
389 op8: OperatorFunction<G, H>,
390 op9: OperatorFunction<H, I>
391 ): Observable<I>;
392 pipe<A, B, C, D, E, F, G, H, I>(
393 op1: OperatorFunction<T, A>,
394 op2: OperatorFunction<A, B>,
395 op3: OperatorFunction<B, C>,
396 op4: OperatorFunction<C, D>,
397 op5: OperatorFunction<D, E>,
398 op6: OperatorFunction<E, F>,
399 op7: OperatorFunction<F, G>,
400 op8: OperatorFunction<G, H>,
401 op9: OperatorFunction<H, I>,
402 ...operations: OperatorFunction<any, any>[]
403 ): Observable<unknown>;
404 /* tslint:enable:max-line-length */
405
406 /**
407 * Used to stitch together functional operators into a chain.
408 *
409 * ## Example
410 *
411 * ```ts
412 * import { interval, filter, map, scan } from 'rxjs';
413 *
414 * interval(1000)
415 * .pipe(
416 * filter(x => x % 2 === 0),
417 * map(x => x + x),
418 * scan((acc, x) => acc + x)
419 * )
420 * .subscribe(x => console.log(x));
421 * ```
422 *
423 * @return The Observable result of all the operators having been called
424 * in the order they were passed in.
425 */
426 pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
427 return pipeFromArray(operations)(this);
428 }
429
430 /* tslint:disable:max-line-length */
431 /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
432 toPromise(): Promise<T | undefined>;
433 /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
434 toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;
435 /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
436 toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;
437 /* tslint:enable:max-line-length */
438
439 /**
440 * Subscribe to this Observable and get a Promise resolving on
441 * `complete` with the last emission (if any).
442 *
443 * **WARNING**: Only use this with observables you *know* will complete. If the source
444 * observable does not complete, you will end up with a promise that is hung up, and
445 * potentially all of the state of an async function hanging out in memory. To avoid
446 * this situation, look into adding something like {@link timeout}, {@link take},
447 * {@link takeWhile}, or {@link takeUntil} amongst others.
448 *
449 * @param [promiseCtor] a constructor function used to instantiate
450 * the Promise
451 * @return A Promise that resolves with the last value emit, or
452 * rejects on an error. If there were no emissions, Promise
453 * resolves with undefined.
454 * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise
455 */
456 toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {
457 promiseCtor = getPromiseCtor(promiseCtor);
458
459 return new promiseCtor((resolve, reject) => {
460 let value: T | undefined;
461 this.subscribe(
462 (x: T) => (value = x),
463 (err: any) => reject(err),
464 () => resolve(value)
465 );
466 }) as Promise<T | undefined>;
467 }
468 }
469
470 /**
471 * Decides between a passed promise constructor from consuming code,
472 * A default configured promise constructor, and the native promise
473 * constructor and returns it. If nothing can be found, it will throw
474 * an error.
475 * @param promiseCtor The optional promise constructor to passed by consuming code
476 */
477 function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
478 return promiseCtor ?? config.Promise ?? Promise;
479 }
480
481 function isObserver<T>(value: any): value is Observer<T> {
482 return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
483 }
484
485 function isSubscriber<T>(value: any): value is Subscriber<T> {
486 return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
487 }