BoundCallbackObservable.js 11 KB

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