BoundCallbackObservable.js 13KB

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