Observable.js 13 KB

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