Observable.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { PartialObserver } from './Observer';
  2. import { Operator } from './Operator';
  3. import { Subscriber } from './Subscriber';
  4. import { Subscription, AnonymousSubscription, TeardownLogic } from './Subscription';
  5. import { root } from './util/root';
  6. import { toSubscriber } from './util/toSubscriber';
  7. import { IfObservable } from './observable/IfObservable';
  8. import { ErrorObservable } from './observable/ErrorObservable';
  9. import { observable as Symbol_observable } from './symbol/observable';
  10. import { OperatorFunction } from './interfaces';
  11. import { pipeFromArray } from './util/pipe';
  12. export interface Subscribable<T> {
  13. subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
  14. error?: (error: any) => void,
  15. complete?: () => void): AnonymousSubscription;
  16. }
  17. export type SubscribableOrPromise<T> = Subscribable<T> | PromiseLike<T>;
  18. export type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T>;
  19. /**
  20. * A representation of any set of values over any amount of time. This is the most basic building block
  21. * of RxJS.
  22. *
  23. * @class Observable<T>
  24. */
  25. export class Observable<T> implements Subscribable<T> {
  26. public _isScalar: boolean = false;
  27. /** @deprecated internal use only */ public source: Observable<any>;
  28. protected operator: Operator<any, T>;
  29. /**
  30. * @constructor
  31. * @param {Function} subscribe the function that is called when the Observable is
  32. * initially subscribed to. This function is given a Subscriber, to which new values
  33. * can be `next`ed, or an `error` method can be called to raise an error, or
  34. * `complete` can be called to notify of a successful completion.
  35. */
  36. constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
  37. if (subscribe) {
  38. this._subscribe = subscribe;
  39. }
  40. }
  41. // HACK: Since TypeScript inherits static properties too, we have to
  42. // fight against TypeScript here so Subject can have a different static create signature
  43. /**
  44. * Creates a new cold Observable by calling the Observable constructor
  45. * @static true
  46. * @owner Observable
  47. * @method create
  48. * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
  49. * @return {Observable} a new cold observable
  50. */
  51. static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
  52. return new Observable<T>(subscribe);
  53. }
  54. /**
  55. * Creates a new Observable, with this Observable as the source, and the passed
  56. * operator defined as the new observable's operator.
  57. * @method lift
  58. * @param {Operator} operator the operator defining the operation to take on the observable
  59. * @return {Observable} a new observable with the Operator applied
  60. */
  61. lift<R>(operator: Operator<T, R>): Observable<R> {
  62. const observable = new Observable<R>();
  63. observable.source = this;
  64. observable.operator = operator;
  65. return observable;
  66. }
  67. subscribe(observer?: PartialObserver<T>): Subscription;
  68. subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
  69. /**
  70. * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
  71. *
  72. * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
  73. *
  74. * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
  75. * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
  76. * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
  77. * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
  78. * thought.
  79. *
  80. * Apart from starting the execution of an Observable, this method allows you to listen for values
  81. * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
  82. * following ways.
  83. *
  84. * The first way is creating an object that implements {@link Observer} interface. It should have methods
  85. * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
  86. * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
  87. * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
  88. * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
  89. * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
  90. * be left uncaught.
  91. *
  92. * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
  93. * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
  94. * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
  95. * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
  96. * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
  97. * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
  98. *
  99. * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
  100. * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
  101. * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
  102. * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
  103. *
  104. * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
  105. * It is an Observable itself that decides when these functions will be called. For example {@link of}
  106. * by default emits all its values synchronously. Always check documentation for how given Observable
  107. * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
  108. *
  109. * @example <caption>Subscribe with an Observer</caption>
  110. * const sumObserver = {
  111. * sum: 0,
  112. * next(value) {
  113. * console.log('Adding: ' + value);
  114. * this.sum = this.sum + value;
  115. * },
  116. * error() { // We actually could just remove this method,
  117. * }, // since we do not really care about errors right now.
  118. * complete() {
  119. * console.log('Sum equals: ' + this.sum);
  120. * }
  121. * };
  122. *
  123. * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
  124. * .subscribe(sumObserver);
  125. *
  126. * // Logs:
  127. * // "Adding: 1"
  128. * // "Adding: 2"
  129. * // "Adding: 3"
  130. * // "Sum equals: 6"
  131. *
  132. *
  133. * @example <caption>Subscribe with functions</caption>
  134. * let sum = 0;
  135. *
  136. * Rx.Observable.of(1, 2, 3)
  137. * .subscribe(
  138. * function(value) {
  139. * console.log('Adding: ' + value);
  140. * sum = sum + value;
  141. * },
  142. * undefined,
  143. * function() {
  144. * console.log('Sum equals: ' + sum);
  145. * }
  146. * );
  147. *
  148. * // Logs:
  149. * // "Adding: 1"
  150. * // "Adding: 2"
  151. * // "Adding: 3"
  152. * // "Sum equals: 6"
  153. *
  154. *
  155. * @example <caption>Cancel a subscription</caption>
  156. * const subscription = Rx.Observable.interval(1000).subscribe(
  157. * num => console.log(num),
  158. * undefined,
  159. * () => console.log('completed!') // Will not be called, even
  160. * ); // when cancelling subscription
  161. *
  162. *
  163. * setTimeout(() => {
  164. * subscription.unsubscribe();
  165. * console.log('unsubscribed!');
  166. * }, 2500);
  167. *
  168. * // Logs:
  169. * // 0 after 1s
  170. * // 1 after 2s
  171. * // "unsubscribed!" after 2.5s
  172. *
  173. *
  174. * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
  175. * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
  176. * Observable.
  177. * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
  178. * the error will be thrown as unhandled.
  179. * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
  180. * @return {ISubscription} a subscription reference to the registered handlers
  181. * @method subscribe
  182. */
  183. subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
  184. error?: (error: any) => void,
  185. complete?: () => void): Subscription {
  186. const { operator } = this;
  187. const sink = toSubscriber(observerOrNext, error, complete);
  188. if (operator) {
  189. operator.call(sink, this.source);
  190. } else {
  191. sink.add(this.source || !sink.syncErrorThrowable ? this._subscribe(sink) : this._trySubscribe(sink));
  192. }
  193. if (sink.syncErrorThrowable) {
  194. sink.syncErrorThrowable = false;
  195. if (sink.syncErrorThrown) {
  196. throw sink.syncErrorValue;
  197. }
  198. }
  199. return sink;
  200. }
  201. protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {
  202. try {
  203. return this._subscribe(sink);
  204. } catch (err) {
  205. sink.syncErrorThrown = true;
  206. sink.syncErrorValue = err;
  207. sink.error(err);
  208. }
  209. }
  210. /**
  211. * @method forEach
  212. * @param {Function} next a handler for each value emitted by the observable
  213. * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
  214. * @return {Promise} a promise that either resolves on observable completion or
  215. * rejects with the handled error
  216. */
  217. forEach(next: (value: T) => void, PromiseCtor?: typeof Promise): Promise<void> {
  218. if (!PromiseCtor) {
  219. if (root.Rx && root.Rx.config && root.Rx.config.Promise) {
  220. PromiseCtor = root.Rx.config.Promise;
  221. } else if (root.Promise) {
  222. PromiseCtor = root.Promise;
  223. }
  224. }
  225. if (!PromiseCtor) {
  226. throw new Error('no Promise impl found');
  227. }
  228. return new PromiseCtor<void>((resolve, reject) => {
  229. // Must be declared in a separate statement to avoid a RefernceError when
  230. // accessing subscription below in the closure due to Temporal Dead Zone.
  231. let subscription: Subscription;
  232. subscription = this.subscribe((value) => {
  233. if (subscription) {
  234. // if there is a subscription, then we can surmise
  235. // the next handling is asynchronous. Any errors thrown
  236. // need to be rejected explicitly and unsubscribe must be
  237. // called manually
  238. try {
  239. next(value);
  240. } catch (err) {
  241. reject(err);
  242. subscription.unsubscribe();
  243. }
  244. } else {
  245. // if there is NO subscription, then we're getting a nexted
  246. // value synchronously during subscription. We can just call it.
  247. // If it errors, Observable's `subscribe` will ensure the
  248. // unsubscription logic is called, then synchronously rethrow the error.
  249. // After that, Promise will trap the error and send it
  250. // down the rejection path.
  251. next(value);
  252. }
  253. }, reject, resolve);
  254. });
  255. }
  256. /** @deprecated internal use only */ _subscribe(subscriber: Subscriber<any>): TeardownLogic {
  257. return this.source.subscribe(subscriber);
  258. }
  259. // `if` and `throw` are special snow flakes, the compiler sees them as reserved words
  260. static if: typeof IfObservable.create;
  261. static throw: typeof ErrorObservable.create;
  262. /**
  263. * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
  264. * @method Symbol.observable
  265. * @return {Observable} this instance of the observable
  266. */
  267. [Symbol_observable]() {
  268. return this;
  269. }
  270. /* tslint:disable:max-line-length */
  271. pipe(): Observable<T>
  272. pipe<A>(op1: OperatorFunction<T, A>): Observable<A>
  273. pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>
  274. pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>
  275. pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>
  276. 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>
  277. 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>
  278. 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>
  279. 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>
  280. 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>
  281. pipe<R>(...operations: OperatorFunction<T, R>[]): Observable<R>
  282. /* tslint:enable:max-line-length */
  283. /**
  284. * Used to stitch together functional operators into a chain.
  285. * @method pipe
  286. * @return {Observable} the Observable result of all of the operators having
  287. * been called in the order they were passed in.
  288. *
  289. * @example
  290. *
  291. * import { map, filter, scan } from 'rxjs/operators';
  292. *
  293. * Rx.Observable.interval(1000)
  294. * .pipe(
  295. * filter(x => x % 2 === 0),
  296. * map(x => x + x),
  297. * scan((acc, x) => acc + x)
  298. * )
  299. * .subscribe(x => console.log(x))
  300. */
  301. pipe<R>(...operations: OperatorFunction<T, R>[]): Observable<R> {
  302. if (operations.length === 0) {
  303. return this as any;
  304. }
  305. return pipeFromArray(operations)(this);
  306. }
  307. /* tslint:disable:max-line-length */
  308. toPromise<T>(this: Observable<T>): Promise<T>;
  309. toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;
  310. toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;
  311. /* tslint:enable:max-line-length */
  312. toPromise(PromiseCtor?: PromiseConstructorLike) {
  313. if (!PromiseCtor) {
  314. if (root.Rx && root.Rx.config && root.Rx.config.Promise) {
  315. PromiseCtor = root.Rx.config.Promise;
  316. } else if (root.Promise) {
  317. PromiseCtor = root.Promise;
  318. }
  319. }
  320. if (!PromiseCtor) {
  321. throw new Error('no Promise impl found');
  322. }
  323. return new PromiseCtor((resolve, reject) => {
  324. let value: any;
  325. this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));
  326. }) as Promise<T>;
  327. }
  328. }