import { Operator } from './Operator'; import { Subscriber } from './Subscriber'; import { Subscription } from './Subscription'; import { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types'; import { canReportError } from './util/canReportError'; import { toSubscriber } from './util/toSubscriber'; import { iif } from './observable/iif'; import { throwError } from './observable/throwError'; import { observable as Symbol_observable } from './symbol/observable'; import { pipeFromArray } from './util/pipe'; import { config } from './config'; /** * A representation of any set of values over any amount of time. This is the most basic building block * of RxJS. * * @class Observable */ export class Observable implements Subscribable { /** Internal implementation detail, do not use directly. */ public _isScalar: boolean = false; /** @deprecated This is an internal implementation detail, do not use. */ source: Observable; /** @deprecated This is an internal implementation detail, do not use. */ operator: Operator; /** * @constructor * @param {Function} subscribe the function that is called when the Observable is * initially subscribed to. This function is given a Subscriber, to which new values * can be `next`ed, or an `error` method can be called to raise an error, or * `complete` can be called to notify of a successful completion. */ constructor(subscribe?: (this: Observable, subscriber: Subscriber) => TeardownLogic) { if (subscribe) { this._subscribe = subscribe; } } // HACK: Since TypeScript inherits static properties too, we have to // fight against TypeScript here so Subject can have a different static create signature /** * Creates a new cold Observable by calling the Observable constructor * @static true * @owner Observable * @method create * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor * @return {Observable} a new cold observable * @nocollapse * @deprecated use new Observable() instead */ static create: Function = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => { return new Observable(subscribe); } /** * Creates a new Observable, with this Observable as the source, and the passed * operator defined as the new observable's operator. * @method lift * @param {Operator} operator the operator defining the operation to take on the observable * @return {Observable} a new observable with the Operator applied */ lift(operator: Operator): Observable { const observable = new Observable(); observable.source = this; observable.operator = operator; return observable; } subscribe(observer?: PartialObserver): Subscription; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription; /** @deprecated Use an observer instead of an error callback */ subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription; subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; /** * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. * * Use it when you have all these Observables, but still nothing is happening. * * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It * might be for example a function that you passed to Observable's constructor, but most of the time it is * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often * the thought. * * Apart from starting the execution of an Observable, this method allows you to listen for values * that an Observable emits, as well as for when it completes or errors. You can achieve this in two * of the following ways. * * The first way is creating an object that implements {@link Observer} interface. It should have methods * defined by that interface, but note that it should be just a regular JavaScript object, which you can create * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also * that your object does not have to implement all methods. If you find yourself creating a method that doesn't * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will * be left uncaught. * * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods. * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer, * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`, * since `subscribe` recognizes these functions by where they were placed in function call. When it comes * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown. * * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object. * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable. * * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously. * It is an Observable itself that decides when these functions will be called. For example {@link of} * by default emits all its values synchronously. Always check documentation for how given Observable * will behave when subscribed and if its default behavior can be modified with a `scheduler`. * * ## Example * ### Subscribe with an Observer * ```ts * import { of } from 'rxjs'; * * const sumObserver = { * sum: 0, * next(value) { * console.log('Adding: ' + value); * this.sum = this.sum + value; * }, * error() { * // We actually could just remove this method, * // since we do not really care about errors right now. * }, * complete() { * console.log('Sum equals: ' + this.sum); * } * }; * * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes. * .subscribe(sumObserver); * * // Logs: * // "Adding: 1" * // "Adding: 2" * // "Adding: 3" * // "Sum equals: 6" * ``` * * ### Subscribe with functions * ```ts * import { of } from 'rxjs' * * let sum = 0; * * of(1, 2, 3).subscribe( * value => { * console.log('Adding: ' + value); * sum = sum + value; * }, * undefined, * () => console.log('Sum equals: ' + sum) * ); * * // Logs: * // "Adding: 1" * // "Adding: 2" * // "Adding: 3" * // "Sum equals: 6" * ``` * * ### Cancel a subscription * ```ts * import { interval } from 'rxjs'; * * const subscription = interval(1000).subscribe( * num => console.log(num), * undefined, * () => { * // Will not be called, even when cancelling subscription. * console.log('completed!'); * } * ); * * setTimeout(() => { * subscription.unsubscribe(); * console.log('unsubscribed!'); * }, 2500); * * // Logs: * // 0 after 1s * // 1 after 2s * // "unsubscribed!" after 2.5s * ``` * * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called, * or the first of three possible handlers, which is the handler for each value emitted from the subscribed * Observable. * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided, * the error will be thrown as unhandled. * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion. * @return {ISubscription} a subscription reference to the registered handlers * @method subscribe */ subscribe(observerOrNext?: PartialObserver | ((value: T) => void), error?: (error: any) => void, complete?: () => void): Subscription { const { operator } = this; const sink = toSubscriber(observerOrNext, error, complete); if (operator) { sink.add(operator.call(sink, this.source)); } else { sink.add( this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? this._subscribe(sink) : this._trySubscribe(sink) ); } if (config.useDeprecatedSynchronousErrorHandling) { if (sink.syncErrorThrowable) { sink.syncErrorThrowable = false; if (sink.syncErrorThrown) { throw sink.syncErrorValue; } } } return sink; } /** @deprecated This is an internal implementation detail, do not use. */ _trySubscribe(sink: Subscriber): TeardownLogic { try { return this._subscribe(sink); } catch (err) { if (config.useDeprecatedSynchronousErrorHandling) { sink.syncErrorThrown = true; sink.syncErrorValue = err; } if (canReportError(sink)) { sink.error(err); } else { console.warn(err); } } } /** * @method forEach * @param {Function} next a handler for each value emitted by the observable * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise * @return {Promise} a promise that either resolves on observable completion or * rejects with the handled error */ forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise { promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor((resolve, reject) => { // Must be declared in a separate statement to avoid a ReferenceError when // accessing subscription below in the closure due to Temporal Dead Zone. let subscription: Subscription; subscription = this.subscribe((value) => { try { next(value); } catch (err) { reject(err); if (subscription) { subscription.unsubscribe(); } } }, reject, resolve); }) as Promise; } /** @internal This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber): TeardownLogic { const { source } = this; return source && source.subscribe(subscriber); } // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in // favor of iif and throwError functions. /** * @nocollapse * @deprecated In favor of iif creation function: import { iif } from 'rxjs'; */ static if: typeof iif; /** * @nocollapse * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs'; */ static throw: typeof throwError; /** * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable * @method Symbol.observable * @return {Observable} this instance of the observable */ [Symbol_observable]() { return this; } /* tslint:disable:max-line-length */ pipe(): Observable; pipe(op1: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction, op6: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction, op6: OperatorFunction, op7: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction, op6: OperatorFunction, op7: OperatorFunction, op8: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction, op6: OperatorFunction, op7: OperatorFunction, op8: OperatorFunction, op9: OperatorFunction): Observable; pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction, op4: OperatorFunction, op5: OperatorFunction, op6: OperatorFunction, op7: OperatorFunction, op8: OperatorFunction, op9: OperatorFunction, ...operations: OperatorFunction[]): Observable<{}>; /* tslint:enable:max-line-length */ /** * Used to stitch together functional operators into a chain. * @method pipe * @return {Observable} the Observable result of all of the operators having * been called in the order they were passed in. * * ### Example * ```ts * import { interval } from 'rxjs'; * import { map, filter, scan } from 'rxjs/operators'; * * interval(1000) * .pipe( * filter(x => x % 2 === 0), * map(x => x + x), * scan((acc, x) => acc + x) * ) * .subscribe(x => console.log(x)) * ``` */ pipe(...operations: OperatorFunction[]): Observable { if (operations.length === 0) { return this as any; } return pipeFromArray(operations)(this); } /* tslint:disable:max-line-length */ toPromise(this: Observable): Promise; toPromise(this: Observable, PromiseCtor: typeof Promise): Promise; toPromise(this: Observable, PromiseCtor: PromiseConstructorLike): Promise; /* tslint:enable:max-line-length */ toPromise(promiseCtor?: PromiseConstructorLike): Promise { promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor((resolve, reject) => { let value: any; this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value)); }) as Promise; } } /** * Decides between a passed promise constructor from consuming code, * A default configured promise constructor, and the native promise * constructor and returns it. If nothing can be found, it will throw * an error. * @param promiseCtor The optional promise constructor to passed by consuming code */ function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) { if (!promiseCtor) { promiseCtor = config.Promise || Promise; } if (!promiseCtor) { throw new Error('no Promise impl found'); } return promiseCtor; }