1 import { Operator } from './Operator';
2 import { Subscriber } from './Subscriber';
3 import { Subscription } from './Subscription';
4 import { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';
5 import { canReportError } from './util/canReportError';
6 import { toSubscriber } from './util/toSubscriber';
7 import { iif } from './observable/iif';
8 import { throwError } from './observable/throwError';
9 import { observable as Symbol_observable } from './symbol/observable';
10 import { pipeFromArray } from './util/pipe';
11 import { config } from './config';
14 * A representation of any set of values over any amount of time. This is the most basic building block
17 * @class Observable<T>
19 export class Observable<T> implements Subscribable<T> {
21 /** Internal implementation detail, do not use directly. */
22 public _isScalar: boolean = false;
24 /** @deprecated This is an internal implementation detail, do not use. */
25 source: Observable<any>;
27 /** @deprecated This is an internal implementation detail, do not use. */
28 operator: Operator<any, T>;
32 * @param {Function} subscribe the function that is called when the Observable is
33 * initially subscribed to. This function is given a Subscriber, to which new values
34 * can be `next`ed, or an `error` method can be called to raise an error, or
35 * `complete` can be called to notify of a successful completion.
37 constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
39 this._subscribe = subscribe;
43 // HACK: Since TypeScript inherits static properties too, we have to
44 // fight against TypeScript here so Subject can have a different static create signature
46 * Creates a new cold Observable by calling the Observable constructor
50 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
51 * @return {Observable} a new cold observable
53 * @deprecated use new Observable() instead
55 static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
56 return new Observable<T>(subscribe);
60 * Creates a new Observable, with this Observable as the source, and the passed
61 * operator defined as the new observable's operator.
63 * @param {Operator} operator the operator defining the operation to take on the observable
64 * @return {Observable} a new observable with the Operator applied
66 lift<R>(operator: Operator<T, R>): Observable<R> {
67 const observable = new Observable<R>();
68 observable.source = this;
69 observable.operator = operator;
73 subscribe(observer?: PartialObserver<T>): Subscription;
74 /** @deprecated Use an observer instead of a complete callback */
75 subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;
76 /** @deprecated Use an observer instead of an error callback */
77 subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
78 /** @deprecated Use an observer instead of a complete callback */
79 subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;
80 subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
82 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
84 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
86 * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
87 * might be for example a function that you passed to Observable's constructor, but most of the time it is
88 * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
89 * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
92 * Apart from starting the execution of an Observable, this method allows you to listen for values
93 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
94 * of the following ways.
96 * The first way is creating an object that implements {@link Observer} interface. It should have methods
97 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
98 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
99 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
100 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
101 * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will
104 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
105 * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
106 * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,
107 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
108 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
109 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
111 * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
112 * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
113 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
114 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
116 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
117 * It is an Observable itself that decides when these functions will be called. For example {@link of}
118 * by default emits all its values synchronously. Always check documentation for how given Observable
119 * will behave when subscribed and if its default behavior can be modified with a `scheduler`.
122 * ### Subscribe with an Observer
124 * import { of } from 'rxjs';
126 * const sumObserver = {
129 * console.log('Adding: ' + value);
130 * this.sum = this.sum + value;
133 * // We actually could just remove this method,
134 * // since we do not really care about errors right now.
137 * console.log('Sum equals: ' + this.sum);
141 * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
142 * .subscribe(sumObserver);
151 * ### Subscribe with functions
153 * import { of } from 'rxjs'
157 * of(1, 2, 3).subscribe(
159 * console.log('Adding: ' + value);
163 * () => console.log('Sum equals: ' + sum)
173 * ### Cancel a subscription
175 * import { interval } from 'rxjs';
177 * const subscription = interval(1000).subscribe(
178 * num => console.log(num),
181 * // Will not be called, even when cancelling subscription.
182 * console.log('completed!');
187 * subscription.unsubscribe();
188 * console.log('unsubscribed!');
194 * // "unsubscribed!" after 2.5s
197 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
198 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
200 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
201 * the error will be thrown as unhandled.
202 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
203 * @return {ISubscription} a subscription reference to the registered handlers
206 subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
207 error?: (error: any) => void,
208 complete?: () => void): Subscription {
210 const { operator } = this;
211 const sink = toSubscriber(observerOrNext, error, complete);
214 sink.add(operator.call(sink, this.source));
217 this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
218 this._subscribe(sink) :
219 this._trySubscribe(sink)
223 if (config.useDeprecatedSynchronousErrorHandling) {
224 if (sink.syncErrorThrowable) {
225 sink.syncErrorThrowable = false;
226 if (sink.syncErrorThrown) {
227 throw sink.syncErrorValue;
235 /** @deprecated This is an internal implementation detail, do not use. */
236 _trySubscribe(sink: Subscriber<T>): TeardownLogic {
238 return this._subscribe(sink);
240 if (config.useDeprecatedSynchronousErrorHandling) {
241 sink.syncErrorThrown = true;
242 sink.syncErrorValue = err;
244 if (canReportError(sink)) {
254 * @param {Function} next a handler for each value emitted by the observable
255 * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise
256 * @return {Promise} a promise that either resolves on observable completion or
257 * rejects with the handled error
259 forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
260 promiseCtor = getPromiseCtor(promiseCtor);
262 return new promiseCtor<void>((resolve, reject) => {
263 // Must be declared in a separate statement to avoid a ReferenceError when
264 // accessing subscription below in the closure due to Temporal Dead Zone.
265 let subscription: Subscription;
266 subscription = this.subscribe((value) => {
272 subscription.unsubscribe();
279 /** @internal This is an internal implementation detail, do not use. */
280 _subscribe(subscriber: Subscriber<any>): TeardownLogic {
281 const { source } = this;
282 return source && source.subscribe(subscriber);
285 // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in
286 // favor of iif and throwError functions.
289 * @deprecated In favor of iif creation function: import { iif } from 'rxjs';
291 static if: typeof iif;
294 * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';
296 static throw: typeof throwError;
299 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
300 * @method Symbol.observable
301 * @return {Observable} this instance of the observable
303 [Symbol_observable]() {
307 /* tslint:disable:max-line-length */
308 pipe(): Observable<T>;
309 pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
310 pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
311 pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
312 pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;
313 pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;
314 pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;
315 pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;
316 pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;
317 pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;
318 pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;
319 /* tslint:enable:max-line-length */
322 * Used to stitch together functional operators into a chain.
324 * @return {Observable} the Observable result of all of the operators having
325 * been called in the order they were passed in.
329 * import { interval } from 'rxjs';
330 * import { map, filter, scan } from 'rxjs/operators';
334 * filter(x => x % 2 === 0),
336 * scan((acc, x) => acc + x)
338 * .subscribe(x => console.log(x))
341 pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
342 if (operations.length === 0) {
346 return pipeFromArray(operations)(this);
349 /* tslint:disable:max-line-length */
350 toPromise<T>(this: Observable<T>): Promise<T>;
351 toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;
352 toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;
353 /* tslint:enable:max-line-length */
355 toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {
356 promiseCtor = getPromiseCtor(promiseCtor);
358 return new promiseCtor((resolve, reject) => {
360 this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));
366 * Decides between a passed promise constructor from consuming code,
367 * A default configured promise constructor, and the native promise
368 * constructor and returns it. If nothing can be found, it will throw
370 * @param promiseCtor The optional promise constructor to passed by consuming code
372 function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
374 promiseCtor = config.Promise || Promise;
378 throw new Error('no Promise impl found');