BoundNodeCallbackObservable.js 12KB

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