rx.lite.extras.compat.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. // Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
  2. ;(function (factory) {
  3. var objectTypes = {
  4. 'function': true,
  5. 'object': true
  6. };
  7. function checkGlobal(value) {
  8. return (value && value.Object === Object) ? value : null;
  9. }
  10. var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
  11. var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
  12. var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
  13. var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  14. var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  15. var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
  16. var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  17. var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
  18. // Because of build optimizers
  19. if (typeof define === 'function' && define.amd) {
  20. define(['./rx.lite.compat'], function (Rx, exports) {
  21. return factory(root, exports, Rx);
  22. });
  23. } else if (typeof module === 'object' && module && module.exports === freeExports) {
  24. module.exports = factory(root, module.exports, require('rx-lite-compat'));
  25. } else {
  26. root.Rx = factory(root, {}, root.Rx);
  27. }
  28. }.call(this, function (root, exp, Rx, undefined) {
  29. // References
  30. var Observable = Rx.Observable,
  31. observableProto = Observable.prototype,
  32. observableNever = Observable.never,
  33. observableThrow = Observable['throw'],
  34. AnonymousObservable = Rx.AnonymousObservable,
  35. ObservableBase = Rx.ObservableBase,
  36. AnonymousObserver = Rx.AnonymousObserver,
  37. notificationCreateOnNext = Rx.Notification.createOnNext,
  38. notificationCreateOnError = Rx.Notification.createOnError,
  39. notificationCreateOnCompleted = Rx.Notification.createOnCompleted,
  40. Observer = Rx.Observer,
  41. observerCreate = Observer.create,
  42. AbstractObserver = Rx.internals.AbstractObserver,
  43. Subject = Rx.Subject,
  44. internals = Rx.internals,
  45. helpers = Rx.helpers,
  46. ScheduledObserver = internals.ScheduledObserver,
  47. SerialDisposable = Rx.SerialDisposable,
  48. SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
  49. CompositeDisposable = Rx.CompositeDisposable,
  50. BinaryDisposable = Rx.BinaryDisposable,
  51. RefCountDisposable = Rx.RefCountDisposable,
  52. disposableEmpty = Rx.Disposable.empty,
  53. immediateScheduler = Rx.Scheduler.immediate,
  54. defaultKeySerializer = helpers.defaultKeySerializer,
  55. addRef = Rx.internals.addRef,
  56. identity = helpers.identity,
  57. isPromise = helpers.isPromise,
  58. isFunction = helpers.isFunction,
  59. inherits = internals.inherits,
  60. bindCallback = internals.bindCallback,
  61. noop = helpers.noop,
  62. isScheduler = Rx.Scheduler.isScheduler,
  63. observableFromPromise = Observable.fromPromise,
  64. ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
  65. var errorObj = {e: {}};
  66. function tryCatcherGen(tryCatchTarget) {
  67. return function tryCatcher() {
  68. try {
  69. return tryCatchTarget.apply(this, arguments);
  70. } catch (e) {
  71. errorObj.e = e;
  72. return errorObj;
  73. }
  74. };
  75. }
  76. var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
  77. if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
  78. return tryCatcherGen(fn);
  79. };
  80. function thrower(e) {
  81. throw e;
  82. }
  83. function ScheduledDisposable(scheduler, disposable) {
  84. this.scheduler = scheduler;
  85. this.disposable = disposable;
  86. this.isDisposed = false;
  87. }
  88. function scheduleItem(s, self) {
  89. if (!self.isDisposed) {
  90. self.isDisposed = true;
  91. self.disposable.dispose();
  92. }
  93. }
  94. ScheduledDisposable.prototype.dispose = function () {
  95. this.scheduler.schedule(this, scheduleItem);
  96. };
  97. var CheckedObserver = (function (__super__) {
  98. inherits(CheckedObserver, __super__);
  99. function CheckedObserver(observer) {
  100. __super__.call(this);
  101. this._observer = observer;
  102. this._state = 0; // 0 - idle, 1 - busy, 2 - done
  103. }
  104. var CheckedObserverPrototype = CheckedObserver.prototype;
  105. CheckedObserverPrototype.onNext = function (value) {
  106. this.checkAccess();
  107. var res = tryCatch(this._observer.onNext).call(this._observer, value);
  108. this._state = 0;
  109. res === errorObj && thrower(res.e);
  110. };
  111. CheckedObserverPrototype.onError = function (err) {
  112. this.checkAccess();
  113. var res = tryCatch(this._observer.onError).call(this._observer, err);
  114. this._state = 2;
  115. res === errorObj && thrower(res.e);
  116. };
  117. CheckedObserverPrototype.onCompleted = function () {
  118. this.checkAccess();
  119. var res = tryCatch(this._observer.onCompleted).call(this._observer);
  120. this._state = 2;
  121. res === errorObj && thrower(res.e);
  122. };
  123. CheckedObserverPrototype.checkAccess = function () {
  124. if (this._state === 1) { throw new Error('Re-entrancy detected'); }
  125. if (this._state === 2) { throw new Error('Observer completed'); }
  126. if (this._state === 0) { this._state = 1; }
  127. };
  128. return CheckedObserver;
  129. }(Observer));
  130. var ObserveOnObserver = (function (__super__) {
  131. inherits(ObserveOnObserver, __super__);
  132. function ObserveOnObserver(scheduler, observer, cancel) {
  133. __super__.call(this, scheduler, observer);
  134. this._cancel = cancel;
  135. }
  136. ObserveOnObserver.prototype.next = function (value) {
  137. __super__.prototype.next.call(this, value);
  138. this.ensureActive();
  139. };
  140. ObserveOnObserver.prototype.error = function (e) {
  141. __super__.prototype.error.call(this, e);
  142. this.ensureActive();
  143. };
  144. ObserveOnObserver.prototype.completed = function () {
  145. __super__.prototype.completed.call(this);
  146. this.ensureActive();
  147. };
  148. ObserveOnObserver.prototype.dispose = function () {
  149. __super__.prototype.dispose.call(this);
  150. this._cancel && this._cancel.dispose();
  151. this._cancel = null;
  152. };
  153. return ObserveOnObserver;
  154. })(ScheduledObserver);
  155. /**
  156. * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
  157. * If a violation is detected, an Error is thrown from the offending observer method call.
  158. *
  159. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
  160. */
  161. Observer.prototype.checked = function () { return new CheckedObserver(this); };
  162. /**
  163. * Schedules the invocation of observer methods on the given scheduler.
  164. * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
  165. * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
  166. */
  167. Observer.notifyOn = function (scheduler) {
  168. return new ObserveOnObserver(scheduler, this);
  169. };
  170. /**
  171. * Creates an observer from a notification callback.
  172. * @param {Function} handler Action that handles a notification.
  173. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
  174. */
  175. Observer.fromNotifier = function (handler, thisArg) {
  176. var handlerFunc = bindCallback(handler, thisArg, 1);
  177. return new AnonymousObserver(function (x) {
  178. return handlerFunc(notificationCreateOnNext(x));
  179. }, function (e) {
  180. return handlerFunc(notificationCreateOnError(e));
  181. }, function () {
  182. return handlerFunc(notificationCreateOnCompleted());
  183. });
  184. };
  185. /**
  186. * Creates a notification callback from an observer.
  187. * @returns The action that forwards its input notification to the underlying observer.
  188. */
  189. Observer.prototype.toNotifier = function () {
  190. var observer = this;
  191. return function (n) { return n.accept(observer); };
  192. };
  193. /**
  194. * Hides the identity of an observer.
  195. * @returns An observer that hides the identity of the specified observer.
  196. */
  197. Observer.prototype.asObserver = function () {
  198. var source = this;
  199. return new AnonymousObserver(
  200. function (x) { source.onNext(x); },
  201. function (e) { source.onError(e); },
  202. function () { source.onCompleted(); }
  203. );
  204. };
  205. var ObserveOnObservable = (function (__super__) {
  206. inherits(ObserveOnObservable, __super__);
  207. function ObserveOnObservable(source, s) {
  208. this.source = source;
  209. this._s = s;
  210. __super__.call(this);
  211. }
  212. ObserveOnObservable.prototype.subscribeCore = function (o) {
  213. return this.source.subscribe(new ObserveOnObserver(this._s, o));
  214. };
  215. return ObserveOnObservable;
  216. }(ObservableBase));
  217. /**
  218. * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  219. *
  220. * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
  221. * that require to be run on a scheduler, use subscribeOn.
  222. *
  223. * @param {Scheduler} scheduler Scheduler to notify observers on.
  224. * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
  225. */
  226. observableProto.observeOn = function (scheduler) {
  227. return new ObserveOnObservable(this, scheduler);
  228. };
  229. var SubscribeOnObservable = (function (__super__) {
  230. inherits(SubscribeOnObservable, __super__);
  231. function SubscribeOnObservable(source, s) {
  232. this.source = source;
  233. this._s = s;
  234. __super__.call(this);
  235. }
  236. function scheduleMethod(scheduler, state) {
  237. var source = state[0], d = state[1], o = state[2];
  238. d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
  239. }
  240. SubscribeOnObservable.prototype.subscribeCore = function (o) {
  241. var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
  242. d.setDisposable(m);
  243. m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
  244. return d;
  245. };
  246. return SubscribeOnObservable;
  247. }(ObservableBase));
  248. /**
  249. * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
  250. * see the remarks section for more information on the distinction between subscribeOn and observeOn.
  251. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
  252. * callbacks on a scheduler, use observeOn.
  253. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
  254. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
  255. */
  256. observableProto.subscribeOn = function (scheduler) {
  257. return new SubscribeOnObservable(this, scheduler);
  258. };
  259. var GenerateObservable = (function (__super__) {
  260. inherits(GenerateObservable, __super__);
  261. function GenerateObservable(state, cndFn, itrFn, resFn, s) {
  262. this._initialState = state;
  263. this._cndFn = cndFn;
  264. this._itrFn = itrFn;
  265. this._resFn = resFn;
  266. this._s = s;
  267. __super__.call(this);
  268. }
  269. function scheduleRecursive(state, recurse) {
  270. if (state.first) {
  271. state.first = false;
  272. } else {
  273. state.newState = tryCatch(state.self._itrFn)(state.newState);
  274. if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
  275. }
  276. var hasResult = tryCatch(state.self._cndFn)(state.newState);
  277. if (hasResult === errorObj) { return state.o.onError(hasResult.e); }
  278. if (hasResult) {
  279. var result = tryCatch(state.self._resFn)(state.newState);
  280. if (result === errorObj) { return state.o.onError(result.e); }
  281. state.o.onNext(result);
  282. recurse(state);
  283. } else {
  284. state.o.onCompleted();
  285. }
  286. }
  287. GenerateObservable.prototype.subscribeCore = function (o) {
  288. var state = {
  289. o: o,
  290. self: this,
  291. first: true,
  292. newState: this._initialState
  293. };
  294. return this._s.scheduleRecursive(state, scheduleRecursive);
  295. };
  296. return GenerateObservable;
  297. }(ObservableBase));
  298. /**
  299. * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
  300. *
  301. * @example
  302. * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
  303. * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
  304. * @param {Mixed} initialState Initial state.
  305. * @param {Function} condition Condition to terminate generation (upon returning false).
  306. * @param {Function} iterate Iteration step function.
  307. * @param {Function} resultSelector Selector function for results produced in the sequence.
  308. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
  309. * @returns {Observable} The generated sequence.
  310. */
  311. Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
  312. isScheduler(scheduler) || (scheduler = currentThreadScheduler);
  313. return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
  314. };
  315. var UsingObservable = (function (__super__) {
  316. inherits(UsingObservable, __super__);
  317. function UsingObservable(resFn, obsFn) {
  318. this._resFn = resFn;
  319. this._obsFn = obsFn;
  320. __super__.call(this);
  321. }
  322. UsingObservable.prototype.subscribeCore = function (o) {
  323. var disposable = disposableEmpty;
  324. var resource = tryCatch(this._resFn)();
  325. if (resource === errorObj) {
  326. return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
  327. }
  328. resource && (disposable = resource);
  329. var source = tryCatch(this._obsFn)(resource);
  330. if (source === errorObj) {
  331. return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
  332. }
  333. return new BinaryDisposable(source.subscribe(o), disposable);
  334. };
  335. return UsingObservable;
  336. }(ObservableBase));
  337. /**
  338. * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
  339. * @param {Function} resourceFactory Factory function to obtain a resource object.
  340. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
  341. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
  342. */
  343. Observable.using = function (resourceFactory, observableFactory) {
  344. return new UsingObservable(resourceFactory, observableFactory);
  345. };
  346. /**
  347. * Propagates the observable sequence or Promise that reacts first.
  348. * @param {Observable} rightSource Second observable sequence or Promise.
  349. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
  350. */
  351. observableProto.amb = function (rightSource) {
  352. var leftSource = this;
  353. return new AnonymousObservable(function (observer) {
  354. var choice,
  355. leftChoice = 'L', rightChoice = 'R',
  356. leftSubscription = new SingleAssignmentDisposable(),
  357. rightSubscription = new SingleAssignmentDisposable();
  358. isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
  359. function choiceL() {
  360. if (!choice) {
  361. choice = leftChoice;
  362. rightSubscription.dispose();
  363. }
  364. }
  365. function choiceR() {
  366. if (!choice) {
  367. choice = rightChoice;
  368. leftSubscription.dispose();
  369. }
  370. }
  371. var leftSubscribe = observerCreate(
  372. function (left) {
  373. choiceL();
  374. choice === leftChoice && observer.onNext(left);
  375. },
  376. function (e) {
  377. choiceL();
  378. choice === leftChoice && observer.onError(e);
  379. },
  380. function () {
  381. choiceL();
  382. choice === leftChoice && observer.onCompleted();
  383. }
  384. );
  385. var rightSubscribe = observerCreate(
  386. function (right) {
  387. choiceR();
  388. choice === rightChoice && observer.onNext(right);
  389. },
  390. function (e) {
  391. choiceR();
  392. choice === rightChoice && observer.onError(e);
  393. },
  394. function () {
  395. choiceR();
  396. choice === rightChoice && observer.onCompleted();
  397. }
  398. );
  399. leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
  400. rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
  401. return new BinaryDisposable(leftSubscription, rightSubscription);
  402. });
  403. };
  404. function amb(p, c) { return p.amb(c); }
  405. /**
  406. * Propagates the observable sequence or Promise that reacts first.
  407. * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
  408. */
  409. Observable.amb = function () {
  410. var acc = observableNever(), items;
  411. if (Array.isArray(arguments[0])) {
  412. items = arguments[0];
  413. } else {
  414. var len = arguments.length;
  415. items = new Array(items);
  416. for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
  417. }
  418. for (var i = 0, len = items.length; i < len; i++) {
  419. acc = amb(acc, items[i]);
  420. }
  421. return acc;
  422. };
  423. /**
  424. * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
  425. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
  426. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
  427. */
  428. observableProto.onErrorResumeNext = function (second) {
  429. if (!second) { throw new Error('Second observable is required'); }
  430. return onErrorResumeNext([this, second]);
  431. };
  432. var OnErrorResumeNextObservable = (function(__super__) {
  433. inherits(OnErrorResumeNextObservable, __super__);
  434. function OnErrorResumeNextObservable(sources) {
  435. this.sources = sources;
  436. __super__.call(this);
  437. }
  438. function scheduleMethod(state, recurse) {
  439. if (state.pos < state.sources.length) {
  440. var current = state.sources[state.pos++];
  441. isPromise(current) && (current = observableFromPromise(current));
  442. var d = new SingleAssignmentDisposable();
  443. state.subscription.setDisposable(d);
  444. d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));
  445. } else {
  446. state.o.onCompleted();
  447. }
  448. }
  449. OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {
  450. var subscription = new SerialDisposable(),
  451. state = {pos: 0, subscription: subscription, o: o, sources: this.sources },
  452. cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);
  453. return new BinaryDisposable(subscription, cancellable);
  454. };
  455. return OnErrorResumeNextObservable;
  456. }(ObservableBase));
  457. var OnErrorResumeNextObserver = (function(__super__) {
  458. inherits(OnErrorResumeNextObserver, __super__);
  459. function OnErrorResumeNextObserver(state, recurse) {
  460. this._state = state;
  461. this._recurse = recurse;
  462. __super__.call(this);
  463. }
  464. OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };
  465. OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };
  466. OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };
  467. return OnErrorResumeNextObserver;
  468. }(AbstractObserver));
  469. /**
  470. * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
  471. * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
  472. */
  473. var onErrorResumeNext = Observable.onErrorResumeNext = function () {
  474. var sources = [];
  475. if (Array.isArray(arguments[0])) {
  476. sources = arguments[0];
  477. } else {
  478. var len = arguments.length;
  479. sources = new Array(len);
  480. for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
  481. }
  482. return new OnErrorResumeNextObservable(sources);
  483. };
  484. function toArray(x) { return x.toArray(); }
  485. function notEmpty(x) { return x.length > 0; }
  486. /**
  487. * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
  488. * @param {Number} count Length of each buffer.
  489. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
  490. * @returns {Observable} An observable sequence of buffers.
  491. */
  492. observableProto.bufferWithCount = observableProto.bufferCount = function (count, skip) {
  493. typeof skip !== 'number' && (skip = count);
  494. return this.windowWithCount(count, skip)
  495. .flatMap(toArray)
  496. .filter(notEmpty);
  497. };
  498. /**
  499. * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
  500. * @param {Number} count Length of each window.
  501. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
  502. * @returns {Observable} An observable sequence of windows.
  503. */
  504. observableProto.windowWithCount = observableProto.windowCount = function (count, skip) {
  505. var source = this;
  506. +count || (count = 0);
  507. Math.abs(count) === Infinity && (count = 0);
  508. if (count <= 0) { throw new ArgumentOutOfRangeError(); }
  509. skip == null && (skip = count);
  510. +skip || (skip = 0);
  511. Math.abs(skip) === Infinity && (skip = 0);
  512. if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
  513. return new AnonymousObservable(function (observer) {
  514. var m = new SingleAssignmentDisposable(),
  515. refCountDisposable = new RefCountDisposable(m),
  516. n = 0,
  517. q = [];
  518. function createWindow () {
  519. var s = new Subject();
  520. q.push(s);
  521. observer.onNext(addRef(s, refCountDisposable));
  522. }
  523. createWindow();
  524. m.setDisposable(source.subscribe(
  525. function (x) {
  526. for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
  527. var c = n - count + 1;
  528. c >= 0 && c % skip === 0 && q.shift().onCompleted();
  529. ++n % skip === 0 && createWindow();
  530. },
  531. function (e) {
  532. while (q.length > 0) { q.shift().onError(e); }
  533. observer.onError(e);
  534. },
  535. function () {
  536. while (q.length > 0) { q.shift().onCompleted(); }
  537. observer.onCompleted();
  538. }
  539. ));
  540. return refCountDisposable;
  541. }, source);
  542. };
  543. var TakeLastBufferObserver = (function (__super__) {
  544. inherits(TakeLastBufferObserver, __super__);
  545. function TakeLastBufferObserver(o, c) {
  546. this._o = o;
  547. this._c = c;
  548. this._q = [];
  549. __super__.call(this);
  550. }
  551. TakeLastBufferObserver.prototype.next = function (x) {
  552. this._q.push(x);
  553. this._q.length > this._c && this._q.shift();
  554. };
  555. TakeLastBufferObserver.prototype.error = function (e) {
  556. this._o.onError(e);
  557. };
  558. TakeLastBufferObserver.prototype.completed = function () {
  559. this._o.onNext(this._q);
  560. this._o.onCompleted();
  561. };
  562. return TakeLastBufferObserver;
  563. }(AbstractObserver));
  564. /**
  565. * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
  566. *
  567. * @description
  568. * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
  569. * source sequence, this buffer is produced on the result sequence.
  570. * @param {Number} count Number of elements to take from the end of the source sequence.
  571. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
  572. */
  573. observableProto.takeLastBuffer = function (count) {
  574. if (count < 0) { throw new ArgumentOutOfRangeError(); }
  575. var source = this;
  576. return new AnonymousObservable(function (o) {
  577. return source.subscribe(new TakeLastBufferObserver(o, count));
  578. }, source);
  579. };
  580. var DefaultIfEmptyObserver = (function (__super__) {
  581. inherits(DefaultIfEmptyObserver, __super__);
  582. function DefaultIfEmptyObserver(o, d) {
  583. this._o = o;
  584. this._d = d;
  585. this._f = false;
  586. __super__.call(this);
  587. }
  588. DefaultIfEmptyObserver.prototype.next = function (x) {
  589. this._f = true;
  590. this._o.onNext(x);
  591. };
  592. DefaultIfEmptyObserver.prototype.error = function (e) {
  593. this._o.onError(e);
  594. };
  595. DefaultIfEmptyObserver.prototype.completed = function () {
  596. !this._f && this._o.onNext(this._d);
  597. this._o.onCompleted();
  598. };
  599. return DefaultIfEmptyObserver;
  600. }(AbstractObserver));
  601. /**
  602. * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
  603. *
  604. * var res = obs = xs.defaultIfEmpty();
  605. * 2 - obs = xs.defaultIfEmpty(false);
  606. *
  607. * @memberOf Observable#
  608. * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
  609. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
  610. */
  611. observableProto.defaultIfEmpty = function (defaultValue) {
  612. var source = this;
  613. defaultValue === undefined && (defaultValue = null);
  614. return new AnonymousObservable(function (o) {
  615. return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
  616. }, source);
  617. };
  618. // Swap out for Array.findIndex
  619. function arrayIndexOfComparer(array, item, comparer) {
  620. for (var i = 0, len = array.length; i < len; i++) {
  621. if (comparer(array[i], item)) { return i; }
  622. }
  623. return -1;
  624. }
  625. function HashSet(comparer) {
  626. this.comparer = comparer;
  627. this.set = [];
  628. }
  629. HashSet.prototype.push = function(value) {
  630. var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
  631. retValue && this.set.push(value);
  632. return retValue;
  633. };
  634. var DistinctObservable = (function (__super__) {
  635. inherits(DistinctObservable, __super__);
  636. function DistinctObservable(source, keyFn, cmpFn) {
  637. this.source = source;
  638. this._keyFn = keyFn;
  639. this._cmpFn = cmpFn;
  640. __super__.call(this);
  641. }
  642. DistinctObservable.prototype.subscribeCore = function (o) {
  643. return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
  644. };
  645. return DistinctObservable;
  646. }(ObservableBase));
  647. var DistinctObserver = (function (__super__) {
  648. inherits(DistinctObserver, __super__);
  649. function DistinctObserver(o, keyFn, cmpFn) {
  650. this._o = o;
  651. this._keyFn = keyFn;
  652. this._h = new HashSet(cmpFn);
  653. __super__.call(this);
  654. }
  655. DistinctObserver.prototype.next = function (x) {
  656. var key = x;
  657. if (isFunction(this._keyFn)) {
  658. key = tryCatch(this._keyFn)(x);
  659. if (key === errorObj) { return this._o.onError(key.e); }
  660. }
  661. this._h.push(key) && this._o.onNext(x);
  662. };
  663. DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
  664. DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
  665. return DistinctObserver;
  666. }(AbstractObserver));
  667. /**
  668. * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
  669. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
  670. *
  671. * @example
  672. * var res = obs = xs.distinct();
  673. * 2 - obs = xs.distinct(function (x) { return x.id; });
  674. * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
  675. * @param {Function} [keySelector] A function to compute the comparison key for each element.
  676. * @param {Function} [comparer] Used to compare items in the collection.
  677. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
  678. */
  679. observableProto.distinct = function (keySelector, comparer) {
  680. comparer || (comparer = defaultComparer);
  681. return new DistinctObservable(this, keySelector, comparer);
  682. };
  683. /**
  684. * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
  685. * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
  686. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
  687. */
  688. observableProto.singleInstance = function() {
  689. var source = this, hasObservable = false, observable;
  690. function getObservable() {
  691. if (!hasObservable) {
  692. hasObservable = true;
  693. observable = source['finally'](function() { hasObservable = false; }).publish().refCount();
  694. }
  695. return observable;
  696. }
  697. return new AnonymousObservable(function(o) {
  698. return getObservable().subscribe(o);
  699. });
  700. };
  701. return Rx;
  702. }));