BoundCallbackObservable.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. "use strict";
  2. var __extends = (this && this.__extends) || function (d, b) {
  3. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4. function __() { this.constructor = d; }
  5. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6. };
  7. var Observable_1 = require('../Observable');
  8. var tryCatch_1 = require('../util/tryCatch');
  9. var errorObject_1 = require('../util/errorObject');
  10. var AsyncSubject_1 = require('../AsyncSubject');
  11. /**
  12. * We need this JSDoc comment for affecting ESDoc.
  13. * @extends {Ignored}
  14. * @hide true
  15. */
  16. var BoundCallbackObservable = (function (_super) {
  17. __extends(BoundCallbackObservable, _super);
  18. function BoundCallbackObservable(callbackFunc, selector, args, context, scheduler) {
  19. _super.call(this);
  20. this.callbackFunc = callbackFunc;
  21. this.selector = selector;
  22. this.args = args;
  23. this.context = context;
  24. this.scheduler = scheduler;
  25. }
  26. /* tslint:enable:max-line-length */
  27. /**
  28. * Converts a callback API to a function that returns an Observable.
  29. *
  30. * <span class="informal">Give it a function `f` of type `f(x, callback)` and
  31. * it will return a function `g` that when called as `g(x)` will output an
  32. * Observable.</span>
  33. *
  34. * `bindCallback` is not an operator because its input and output are not
  35. * Observables. The input is a function `func` with some parameters, the
  36. * last parameter must be a callback function that `func` calls when it is
  37. * done.
  38. *
  39. * The output of `bindCallback` is a function that takes the same parameters
  40. * as `func`, except the last one (the callback). When the output function
  41. * is called with arguments it will return an Observable. If function `func`
  42. * calls its callback with one argument the Observable will emit that value.
  43. * If on the other hand the callback is called with multiple values the resulting
  44. * Observable will emit an array with said values as arguments.
  45. *
  46. * It is very important to remember that input function `func` is not called
  47. * when the output function is, but rather when the Observable returned by the output
  48. * function is subscribed. This means if `func` makes an AJAX request, that request
  49. * will be made every time someone subscribes to the resulting Observable, but not before.
  50. *
  51. * Optionally, a selector function can be passed to `bindObservable`. The selector function
  52. * takes the same arguments as the callback and returns the value that will be emitted by the Observable.
  53. * Even though by default multiple arguments passed to callback appear in the stream as an array
  54. * the selector function will be called with arguments directly, just as the callback would.
  55. * This means you can imagine the default selector (when one is not provided explicitly)
  56. * as a function that aggregates all its arguments into an array, or simply returns first argument
  57. * if there is only one.
  58. *
  59. * The last optional parameter - {@link Scheduler} - can be used to control when the call
  60. * to `func` happens after someone subscribes to Observable, as well as when results
  61. * passed to callback will be emitted. By default, the subscription to an Observable calls `func`
  62. * synchronously, but using `Scheduler.async` as the last parameter will defer the call to `func`,
  63. * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you use the async Scheduler
  64. * and call `subscribe` on the output Observable all function calls that are currently executing
  65. * will end before `func` is invoked.
  66. *
  67. * By default results passed to the callback are emitted immediately after `func` invokes the callback.
  68. * In particular, if the callback is called synchronously the subscription of the resulting Observable
  69. * will call the `next` function synchronously as well. If you want to defer that call,
  70. * you may use `Scheduler.async` just as before. This means that by using `Scheduler.async` you can
  71. * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.
  72. *
  73. * Note that the Observable created by the output function will always emit a single value
  74. * and then complete immediately. If `func` calls the callback multiple times, values from subsequent
  75. * calls will not appear in the stream. If you need to listen for multiple calls,
  76. * you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.
  77. *
  78. * If `func` depends on some context (`this` property) and is not already bound the context of `func`
  79. * will be the context that the output function has at call time. In particular, if `func`
  80. * is called as a method of some objec and if `func` is not already bound, in order to preserve the context
  81. * it is recommended that the context of the output function is set to that object as well.
  82. *
  83. * If the input function calls its callback in the "node style" (i.e. first argument to callback is
  84. * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}
  85. * provides convenient error handling and probably is a better choice.
  86. * `bindCallback` will treat such functions the same as any other and error parameters
  87. * (whether passed or not) will always be interpreted as regular callback argument.
  88. *
  89. *
  90. * @example <caption>Convert jQuery's getJSON to an Observable API</caption>
  91. * // Suppose we have jQuery.getJSON('/my/url', callback)
  92. * var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
  93. * var result = getJSONAsObservable('/my/url');
  94. * result.subscribe(x => console.log(x), e => console.error(e));
  95. *
  96. *
  97. * @example <caption>Receive an array of arguments passed to a callback</caption>
  98. * someFunction((a, b, c) => {
  99. * console.log(a); // 5
  100. * console.log(b); // 'some string'
  101. * console.log(c); // {someProperty: 'someValue'}
  102. * });
  103. *
  104. * const boundSomeFunction = Rx.Observable.bindCallback(someFunction);
  105. * boundSomeFunction().subscribe(values => {
  106. * console.log(values) // [5, 'some string', {someProperty: 'someValue'}]
  107. * });
  108. *
  109. *
  110. * @example <caption>Use bindCallback with a selector function</caption>
  111. * someFunction((a, b, c) => {
  112. * console.log(a); // 'a'
  113. * console.log(b); // 'b'
  114. * console.log(c); // 'c'
  115. * });
  116. *
  117. * const boundSomeFunction = Rx.Observable.bindCallback(someFunction, (a, b, c) => a + b + c);
  118. * boundSomeFunction().subscribe(value => {
  119. * console.log(value) // 'abc'
  120. * });
  121. *
  122. *
  123. * @example <caption>Compare behaviour with and without async Scheduler</caption>
  124. * function iCallMyCallbackSynchronously(cb) {
  125. * cb();
  126. * }
  127. *
  128. * const boundSyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously);
  129. * const boundAsyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async);
  130. *
  131. * boundSyncFn().subscribe(() => console.log('I was sync!'));
  132. * boundAsyncFn().subscribe(() => console.log('I was async!'));
  133. * console.log('This happened...');
  134. *
  135. * // Logs:
  136. * // I was sync!
  137. * // This happened...
  138. * // I was async!
  139. *
  140. *
  141. * @example <caption>Use bindCallback on an object method</caption>
  142. * const boundMethod = Rx.Observable.bindCallback(someObject.methodWithCallback);
  143. * boundMethod.call(someObject) // make sure methodWithCallback has access to someObject
  144. * .subscribe(subscriber);
  145. *
  146. *
  147. * @see {@link bindNodeCallback}
  148. * @see {@link from}
  149. * @see {@link fromPromise}
  150. *
  151. * @param {function} func A function with a callback as the last parameter.
  152. * @param {function} [selector] A function which takes the arguments from the
  153. * callback and maps them to a value that is emitted on the output Observable.
  154. * @param {Scheduler} [scheduler] The scheduler on which to schedule the
  155. * callbacks.
  156. * @return {function(...params: *): Observable} A function which returns the
  157. * Observable that delivers the same values the callback would deliver.
  158. * @static true
  159. * @name bindCallback
  160. * @owner Observable
  161. */
  162. BoundCallbackObservable.create = function (func, selector, scheduler) {
  163. if (selector === void 0) { selector = undefined; }
  164. return function () {
  165. var args = [];
  166. for (var _i = 0; _i < arguments.length; _i++) {
  167. args[_i - 0] = arguments[_i];
  168. }
  169. return new BoundCallbackObservable(func, selector, args, this, scheduler);
  170. };
  171. };
  172. /** @deprecated internal use only */ BoundCallbackObservable.prototype._subscribe = function (subscriber) {
  173. var callbackFunc = this.callbackFunc;
  174. var args = this.args;
  175. var scheduler = this.scheduler;
  176. var subject = this.subject;
  177. if (!scheduler) {
  178. if (!subject) {
  179. subject = this.subject = new AsyncSubject_1.AsyncSubject();
  180. var handler = function handlerFn() {
  181. var innerArgs = [];
  182. for (var _i = 0; _i < arguments.length; _i++) {
  183. innerArgs[_i - 0] = arguments[_i];
  184. }
  185. var source = handlerFn.source;
  186. var selector = source.selector, subject = source.subject;
  187. if (selector) {
  188. var result_1 = tryCatch_1.tryCatch(selector).apply(this, innerArgs);
  189. if (result_1 === errorObject_1.errorObject) {
  190. subject.error(errorObject_1.errorObject.e);
  191. }
  192. else {
  193. subject.next(result_1);
  194. subject.complete();
  195. }
  196. }
  197. else {
  198. subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
  199. subject.complete();
  200. }
  201. };
  202. // use named function instance to avoid closure.
  203. handler.source = this;
  204. var result = tryCatch_1.tryCatch(callbackFunc).apply(this.context, args.concat(handler));
  205. if (result === errorObject_1.errorObject) {
  206. subject.error(errorObject_1.errorObject.e);
  207. }
  208. }
  209. return subject.subscribe(subscriber);
  210. }
  211. else {
  212. return scheduler.schedule(BoundCallbackObservable.dispatch, 0, { source: this, subscriber: subscriber, context: this.context });
  213. }
  214. };
  215. BoundCallbackObservable.dispatch = function (state) {
  216. var self = this;
  217. var source = state.source, subscriber = state.subscriber, context = state.context;
  218. var callbackFunc = source.callbackFunc, args = source.args, scheduler = source.scheduler;
  219. var subject = source.subject;
  220. if (!subject) {
  221. subject = source.subject = new AsyncSubject_1.AsyncSubject();
  222. var handler = function handlerFn() {
  223. var innerArgs = [];
  224. for (var _i = 0; _i < arguments.length; _i++) {
  225. innerArgs[_i - 0] = arguments[_i];
  226. }
  227. var source = handlerFn.source;
  228. var selector = source.selector, subject = source.subject;
  229. if (selector) {
  230. var result_2 = tryCatch_1.tryCatch(selector).apply(this, innerArgs);
  231. if (result_2 === errorObject_1.errorObject) {
  232. self.add(scheduler.schedule(dispatchError, 0, { err: errorObject_1.errorObject.e, subject: subject }));
  233. }
  234. else {
  235. self.add(scheduler.schedule(dispatchNext, 0, { value: result_2, subject: subject }));
  236. }
  237. }
  238. else {
  239. var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
  240. self.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
  241. }
  242. };
  243. // use named function to pass values in without closure
  244. handler.source = source;
  245. var result = tryCatch_1.tryCatch(callbackFunc).apply(context, args.concat(handler));
  246. if (result === errorObject_1.errorObject) {
  247. subject.error(errorObject_1.errorObject.e);
  248. }
  249. }
  250. self.add(subject.subscribe(subscriber));
  251. };
  252. return BoundCallbackObservable;
  253. }(Observable_1.Observable));
  254. exports.BoundCallbackObservable = BoundCallbackObservable;
  255. function dispatchNext(arg) {
  256. var value = arg.value, subject = arg.subject;
  257. subject.next(value);
  258. subject.complete();
  259. }
  260. function dispatchError(arg) {
  261. var err = arg.err, subject = arg.subject;
  262. subject.error(err);
  263. }
  264. //# sourceMappingURL=BoundCallbackObservable.js.map