BoundNodeCallbackObservable.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 BoundNodeCallbackObservable 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 Node.js-style callback API to a function that returns an
  22. * Observable.
  23. *
  24. * <span class="informal">It's just like {@link bindCallback}, but the
  25. * callback is expected to be of type `callback(error, result)`.</span>
  26. *
  27. * `bindNodeCallback` is not an operator because its input and output are not
  28. * Observables. The input is a function `func` with some parameters, but the
  29. * last parameter must be a callback function that `func` calls when it is
  30. * done. The callback function is expected to follow Node.js conventions,
  31. * where the first argument to the callback is an error object, signaling
  32. * whether call was successful. If that object is passed to callback, it means
  33. * something went wrong.
  34. *
  35. * The output of `bindNodeCallback` is a function that takes the same
  36. * parameters as `func`, except the last one (the callback). When the output
  37. * function is called with arguments, it will return an Observable.
  38. * If `func` calls its callback with error parameter present, Observable will
  39. * error with that value as well. If error parameter is not passed, Observable will emit
  40. * second parameter. If there are more parameters (third and so on),
  41. * Observable will emit an array with all arguments, except first error argument.
  42. *
  43. * Optionally `bindNodeCallback` accepts selector function, which allows you to
  44. * make resulting Observable emit value computed by selector, instead of regular
  45. * callback arguments. It works similarly to {@link bindCallback} selector, but
  46. * Node.js-style error argument will never be passed to that function.
  47. *
  48. * Note that `func` will not be called at the same time output function is,
  49. * but rather whenever resulting Observable is subscribed. By default call to
  50. * `func` will happen synchronously after subscription, but that can be changed
  51. * with proper {@link Scheduler} provided as optional third parameter. Scheduler
  52. * can also control when values from callback will be emitted by Observable.
  53. * To find out more, check out documentation for {@link bindCallback}, where
  54. * Scheduler works exactly the same.
  55. *
  56. * As in {@link bindCallback}, context (`this` property) of input function will be set to context
  57. * of returned function, when it is called.
  58. *
  59. * After Observable emits value, it will complete immediately. This means
  60. * even if `func` calls callback again, values from second and consecutive
  61. * calls will never appear on the stream. If you need to handle functions
  62. * that call callbacks multiple times, check out {@link fromEvent} or
  63. * {@link fromEventPattern} instead.
  64. *
  65. * Note that `bindNodeCallback` can be used in non-Node.js environments as well.
  66. * "Node.js-style" callbacks are just a convention, so if you write for
  67. * browsers or any other environment and API you use implements that callback style,
  68. * `bindNodeCallback` can be safely used on that API functions as well.
  69. *
  70. * Remember that Error object passed to callback does not have to be an instance
  71. * of JavaScript built-in `Error` object. In fact, it does not even have to an object.
  72. * Error parameter of callback function is interpreted as "present", when value
  73. * of that parameter is truthy. It could be, for example, non-zero number, non-empty
  74. * string or boolean `true`. In all of these cases resulting Observable would error
  75. * with that value. This means usually regular style callbacks will fail very often when
  76. * `bindNodeCallback` is used. If your Observable errors much more often then you
  77. * would expect, check if callback really is called in Node.js-style and, if not,
  78. * switch to {@link bindCallback} instead.
  79. *
  80. * Note that even if error parameter is technically present in callback, but its value
  81. * is falsy, it still won't appear in array emitted by Observable or in selector function.
  82. *
  83. *
  84. * @example <caption>Read a file from the filesystem and get the data as an Observable</caption>
  85. * import * as fs from 'fs';
  86. * var readFileAsObservable = Rx.Observable.bindNodeCallback(fs.readFile);
  87. * var result = readFileAsObservable('./roadNames.txt', 'utf8');
  88. * result.subscribe(x => console.log(x), e => console.error(e));
  89. *
  90. *
  91. * @example <caption>Use on function calling callback with multiple arguments</caption>
  92. * someFunction((err, a, b) => {
  93. * console.log(err); // null
  94. * console.log(a); // 5
  95. * console.log(b); // "some string"
  96. * });
  97. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction);
  98. * boundSomeFunction()
  99. * .subscribe(value => {
  100. * console.log(value); // [5, "some string"]
  101. * });
  102. *
  103. *
  104. * @example <caption>Use with selector function</caption>
  105. * someFunction((err, a, b) => {
  106. * console.log(err); // undefined
  107. * console.log(a); // "abc"
  108. * console.log(b); // "DEF"
  109. * });
  110. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction, (a, b) => a + b);
  111. * boundSomeFunction()
  112. * .subscribe(value => {
  113. * console.log(value); // "abcDEF"
  114. * });
  115. *
  116. *
  117. * @example <caption>Use on function calling callback in regular style</caption>
  118. * someFunction(a => {
  119. * console.log(a); // 5
  120. * });
  121. * var boundSomeFunction = Rx.Observable.bindNodeCallback(someFunction);
  122. * boundSomeFunction()
  123. * .subscribe(
  124. * value => {} // never gets called
  125. * err => console.log(err) // 5
  126. *);
  127. *
  128. *
  129. * @see {@link bindCallback}
  130. * @see {@link from}
  131. * @see {@link fromPromise}
  132. *
  133. * @param {function} func Function with a Node.js-style callback as the last parameter.
  134. * @param {function} [selector] A function which takes the arguments from the
  135. * callback and maps those to a value to emit on the output Observable.
  136. * @param {Scheduler} [scheduler] The scheduler on which to schedule the
  137. * callbacks.
  138. * @return {function(...params: *): Observable} A function which returns the
  139. * Observable that delivers the same values the Node.js callback would
  140. * deliver.
  141. * @static true
  142. * @name bindNodeCallback
  143. * @owner Observable
  144. */
  145. static create(func, selector = undefined, scheduler) {
  146. return function (...args) {
  147. return new BoundNodeCallbackObservable(func, selector, args, this, scheduler);
  148. };
  149. }
  150. /** @deprecated internal use only */ _subscribe(subscriber) {
  151. const callbackFunc = this.callbackFunc;
  152. const args = this.args;
  153. const scheduler = this.scheduler;
  154. let subject = this.subject;
  155. if (!scheduler) {
  156. if (!subject) {
  157. subject = this.subject = new AsyncSubject();
  158. const handler = function handlerFn(...innerArgs) {
  159. const source = handlerFn.source;
  160. const { selector, subject } = source;
  161. const err = innerArgs.shift();
  162. if (err) {
  163. subject.error(err);
  164. }
  165. else if (selector) {
  166. const result = tryCatch(selector).apply(this, innerArgs);
  167. if (result === errorObject) {
  168. subject.error(errorObject.e);
  169. }
  170. else {
  171. subject.next(result);
  172. subject.complete();
  173. }
  174. }
  175. else {
  176. subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
  177. subject.complete();
  178. }
  179. };
  180. // use named function instance to avoid closure.
  181. handler.source = this;
  182. const result = tryCatch(callbackFunc).apply(this.context, args.concat(handler));
  183. if (result === errorObject) {
  184. subject.error(errorObject.e);
  185. }
  186. }
  187. return subject.subscribe(subscriber);
  188. }
  189. else {
  190. return scheduler.schedule(dispatch, 0, { source: this, subscriber, context: this.context });
  191. }
  192. }
  193. }
  194. function dispatch(state) {
  195. const self = this;
  196. const { source, subscriber, context } = state;
  197. // XXX: cast to `any` to access to the private field in `source`.
  198. const { callbackFunc, args, scheduler } = source;
  199. let subject = source.subject;
  200. if (!subject) {
  201. subject = source.subject = new AsyncSubject();
  202. const handler = function handlerFn(...innerArgs) {
  203. const source = handlerFn.source;
  204. const { selector, subject } = source;
  205. const err = innerArgs.shift();
  206. if (err) {
  207. self.add(scheduler.schedule(dispatchError, 0, { err, subject }));
  208. }
  209. else 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. self.add(scheduler.schedule(dispatchError, 0, { err: errorObject.e, subject }));
  228. }
  229. }
  230. self.add(subject.subscribe(subscriber));
  231. }
  232. function dispatchNext(arg) {
  233. const { value, subject } = arg;
  234. subject.next(value);
  235. subject.complete();
  236. }
  237. function dispatchError(arg) {
  238. const { err, subject } = arg;
  239. subject.error(err);
  240. }
  241. //# sourceMappingURL=BoundNodeCallbackObservable.js.map