BoundNodeCallbackObservable.js 12 KB

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