Observable.js 12 KB

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