diff --git a/dist/cycle-jsonp-driver.js b/dist/cycle-jsonp-driver.js index 5408de8..d93f087 100644 --- a/dist/cycle-jsonp-driver.js +++ b/dist/cycle-jsonp-driver.js @@ -144,27 +144,23 @@ module.exports = Cycle; },{"rx":2}],2:[function(require,module,exports){ (function (process,global){ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - + ;(function (undefined) { var objectTypes = { - 'boolean': false, 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false + 'object': true }; - var root = (objectTypes[typeof window] && window) || this, + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeSelf = objectTypes[typeof self] && self.Object && self, + freeWindow = objectTypes[typeof window] && window && window.Object && window, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, - freeGlobal = objectTypes[typeof global] && global; + freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; - } + var root = root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; var Rx = { internals: {}, @@ -173,21 +169,16 @@ module.exports = Cycle; }, helpers: { } }; - + // Defaults var noop = Rx.helpers.noop = function () { }, - notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, identity = Rx.helpers.identity = function (x) { return x; }, - pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, - just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, - asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, - not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { @@ -205,46 +196,60 @@ module.exports = Cycle; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} - - Rx.config.longStackSupport = false; - var hasStacks = false; - try { - throw new Error(); - } catch (e) { - hasStacks = !!e.stack; + + var errorObj = {e: {}}; + var tryCatchTarget; + function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } + } + function tryCatch(fn) { + if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } + tryCatchTarget = fn; + return tryCatcher; + } + function thrower(e) { + throw e; } + Rx.config.longStackSupport = false; + var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })(); + hasStacks = !!stacks.e && !!stacks.e.stack; + // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; - - var STACK_JUMP_SEPARATOR = "From previous event:"; - function makeStackTraceLong(error, observable) { - // If possible, transform the error stack trace by removing Node and RxJS - // cruft, then concatenating with the stack trace of `observable`. - if (hasStacks && - observable.stack && - typeof error === "object" && - error !== null && - error.stack && - error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 - ) { - var stacks = []; - for (var o = observable; !!o; o = o.source) { - if (o.stack) { - stacks.unshift(o.stack); - } - } - stacks.unshift(error.stack); + var STACK_JUMP_SEPARATOR = 'From previous event:'; - var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); - error.stack = filterStackString(concatedStacks); + function makeStackTraceLong(error, observable) { + // If possible, transform the error stack trace by removing Node and RxJS + // cruft, then concatenating with the stack trace of `observable`. + if (hasStacks && + observable.stack && + typeof error === 'object' && + error !== null && + error.stack && + error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 + ) { + var stacks = []; + for (var o = observable; !!o; o = o.source) { + if (o.stack) { + stacks.unshift(o.stack); + } + } + stacks.unshift(error.stack); + + var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n'); + error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { - var lines = stackString.split("\n"), - desiredLines = []; + var lines = stackString.split('\n'), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; @@ -252,7 +257,7 @@ module.exports = Cycle; desiredLines.push(line); } } - return desiredLines.join("\n"); + return desiredLines.join('\n'); } function isInternalFrame(stackLine) { @@ -268,8 +273,8 @@ module.exports = Cycle; } function isNodeFrame(stackLine) { - return stackLine.indexOf("(module.js:") !== -1 || - stackLine.indexOf("(node.js:") !== -1; + return stackLine.indexOf('(module.js:') !== -1 || + stackLine.indexOf('(node.js:') !== -1; } function captureLine() { @@ -278,8 +283,8 @@ module.exports = Cycle; try { throw new Error(); } catch (e) { - var lines = e.stack.split("\n"); - var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var lines = e.stack.split('\n'); + var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } @@ -289,45 +294,50 @@ module.exports = Cycle; } function getFileNameAndLineNumber(stackLine) { - // Named functions: "at functionName (filename:lineNumber:columnNumber)" + // Named functions: 'at functionName (filename:lineNumber:columnNumber)' var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } - // Anonymous functions: "at filename:lineNumber:columnNumber" + // Anonymous functions: 'at filename:lineNumber:columnNumber' var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } - // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + // Firefox style: 'function@filename:lineNumber or @filename:lineNumber' var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } - + var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; + this.name = 'EmptyError'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; + this.name = 'ObjectDisposedError'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; + this.name = 'ArgumentOutOfRangeError'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; + this.name = 'NotSupportedError'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; + this.name = 'NotImplementedError'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; @@ -339,7 +349,7 @@ module.exports = Cycle; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; - + // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; @@ -359,7 +369,7 @@ module.exports = Cycle; } Rx.helpers.iterator = $iterator$; - + var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { @@ -385,7 +395,7 @@ module.exports = Cycle; return func.apply(thisArg, arguments); }; }; - + /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', @@ -395,7 +405,7 @@ module.exports = Cycle; 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; - + /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', @@ -670,11 +680,11 @@ module.exports = Cycle; return result; } - + var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; - var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + var inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); @@ -704,26 +714,7 @@ module.exports = Cycle; } return a; } - - var errorObj = {e: {}}; - var tryCatchTarget; - function tryCatcher() { - try { - return tryCatchTarget.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } - } - function tryCatch(fn) { - if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } - tryCatchTarget = fn; - return tryCatcher; - } - function thrower(e) { - throw e; - } - + // Collections function IndexedItem(id, value) { this.id = id; @@ -809,7 +800,7 @@ module.exports = Cycle; return false; }; PriorityQueue.count = 0; - + /** * Represents a group of disposable resources that are disposed together. * @constructor @@ -882,7 +873,7 @@ module.exports = Cycle; } } }; - + /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. @@ -924,7 +915,7 @@ module.exports = Cycle; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; - + // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; @@ -973,7 +964,7 @@ module.exports = Cycle; } old && old.dispose(); }; - + /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ @@ -1031,7 +1022,7 @@ module.exports = Cycle; return RefCountDisposable; })(); - + function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; @@ -1048,7 +1039,7 @@ module.exports = Cycle; ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; - + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; @@ -1073,7 +1064,7 @@ module.exports = Cycle; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; - + /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { @@ -1174,56 +1165,67 @@ module.exports = Cycle; }()); var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; - + (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); + action(state, innerAction); + return group; - function recursiveAction(state1) { - action(state1, function (state2) { - var isAdded = false, isDone = false, - d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { - if (isAdded) { - group.remove(d); - } else { - isDone = true; - } - recursiveAction(state3); - return disposableEmpty; - }); - if (!isDone) { - group.add(d); - isAdded = true; + function innerAction(state2) { + var isAdded = false, isDone = false; + + var d = scheduler.scheduleWithState(state2, scheduleWork); + if (!isDone) { + group.add(d); + isAdded = true; + } + + function scheduleWork(_, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; } - }); + action(state3, innerAction); + return disposableEmpty; + } } - recursiveAction(state); - return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); - function recursiveAction(state1) { - action(state1, function (state2, dueTime1) { - var isAdded = false, isDone = false, - d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { - if (isAdded) { - group.remove(d); - } else { - isDone = true; - } - recursiveAction(state3); - return disposableEmpty; - }); - if (!isDone) { - group.add(d); - isAdded = true; - } - }); - }; - recursiveAction(state); + action(state, innerAction); return group; + + function innerAction(state2, dueTime1) { + var isAdded = false, isDone = false; + + var d = scheduler[method](state2, dueTime1, scheduleWork); + if (!isDone) { + group.add(d); + isAdded = true; + } + + function scheduleWork(_, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + action(state3, innerAction); + return disposableEmpty; + } + } + } + + function invokeRecDateRelative(s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + } + + function invokeRecDateAbsolute(s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); } function scheduleInnerRecursive(action, self) { @@ -1267,9 +1269,7 @@ module.exports = Cycle; * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { - return this._scheduleRelative([state, action], dueTime, function (s, p) { - return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); - }); + return this._scheduleRelative([state, action], dueTime, invokeRecDateRelative); }; /** @@ -1290,12 +1290,10 @@ module.exports = Cycle; * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { - return this._scheduleAbsolute([state, action], dueTime, function (s, p) { - return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); - }); + return this._scheduleAbsolute([state, action], dueTime, invokeRecDateAbsolute); }; }(Scheduler.prototype)); - + (function (schedulerProto) { /** @@ -1323,7 +1321,7 @@ module.exports = Cycle; }; }(Scheduler.prototype)); - + (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. @@ -1334,7 +1332,7 @@ module.exports = Cycle; return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); - + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); @@ -1363,13 +1361,13 @@ module.exports = Cycle; return SchedulePeriodicRecursive; }()); - + /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); - + /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ @@ -1378,7 +1376,7 @@ module.exports = Cycle; function runTrampoline () { while (queue.length > 0) { - var item = queue.dequeue(); + var item = queue.shift(); !item.isCancelled() && item.invoke(); } } @@ -1387,14 +1385,13 @@ module.exports = Cycle; var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { - queue = new PriorityQueue(4); - queue.enqueue(si); + queue = [si]; var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { - queue.enqueue(si); + queue.push(si); } return si.disposable; } @@ -1404,7 +1401,7 @@ module.exports = Cycle; return currentScheduler; }()); - + var scheduleMethod, clearMethod; var localTimer = (function () { @@ -1587,7 +1584,7 @@ module.exports = Cycle; return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); - + var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { @@ -1659,7 +1656,7 @@ module.exports = Cycle; return CatchScheduler; }(Scheduler)); - + /** * Represents a notification to an observer. */ @@ -1752,7 +1749,7 @@ module.exports = Cycle; return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); - + /** * Supports push-style iteration over an observable sequence. */ @@ -1772,7 +1769,11 @@ module.exports = Cycle; * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { - return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + var self = this; + return new AnonymousObserver( + function (x) { self.onNext(x); }, + function (err) { self.onError(err); }, + function () { self.onCompleted(); }); }; /** @@ -1805,12 +1806,13 @@ module.exports = Cycle; * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { + var cb = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { - return handler.call(thisArg, notificationCreateOnNext(x)); + return cb(notificationCreateOnNext(x)); }, function (e) { - return handler.call(thisArg, notificationCreateOnError(e)); + return cb(notificationCreateOnError(e)); }, function () { - return handler.call(thisArg, notificationCreateOnCompleted()); + return cb(notificationCreateOnCompleted()); }); }; @@ -1826,7 +1828,7 @@ module.exports = Cycle; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; - + /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. @@ -1839,7 +1841,6 @@ module.exports = Cycle; */ function AbstractObserver() { this.isStopped = false; - __super__.call(this); } // Must be implemented by other observers @@ -1852,7 +1853,7 @@ module.exports = Cycle; * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { - if (!this.isStopped) { this.next(value); } + !this.isStopped && this.next(value); }; /** @@ -1879,9 +1880,7 @@ module.exports = Cycle; /** * Disposes the observer, causing it to transition to the stopped state. */ - AbstractObserver.prototype.dispose = function () { - this.isStopped = true; - }; + AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { @@ -1895,7 +1894,7 @@ module.exports = Cycle; return AbstractObserver; }(Observer)); - + /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ @@ -1940,7 +1939,7 @@ module.exports = Cycle; return AnonymousObserver; }(AbstractObserver)); - + var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); @@ -1981,7 +1980,7 @@ module.exports = Cycle; return CheckedObserver; }(Observer)); - + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); @@ -2011,13 +2010,13 @@ module.exports = Cycle; }; ScheduledObserver.prototype.ensureActive = function () { - var isOwner = false, parent = this; + var isOwner = false; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { - this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this, function (parent, self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); @@ -2025,14 +2024,13 @@ module.exports = Cycle; parent.isAcquired = false; return; } - try { - work(); - } catch (ex) { + var res = tryCatch(work)(); + if (res === errorObj) { parent.queue = []; parent.hasFaulted = true; - throw ex; + return thrower(res.e); } - self(); + self(parent); })); } }; @@ -2044,7 +2042,7 @@ module.exports = Cycle; return ScheduledObserver; }(AbstractObserver)); - + var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); @@ -2076,7 +2074,7 @@ module.exports = Cycle; return ObserveOnObserver; })(ScheduledObserver); - + var observableProto; /** @@ -2084,25 +2082,23 @@ module.exports = Cycle; */ var Observable = Rx.Observable = (function () { - function Observable(subscribe) { - if (Rx.config.longStackSupport && hasStacks) { - try { - throw new Error(); - } catch (e) { - this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); - } - - var self = this; - this._subscribe = function (observer) { - var oldOnError = observer.onError.bind(observer); + function makeSubscribe(self, subscribe) { + return function (o) { + var oldOnError = o.onError; + o.onError = function (e) { + makeStackTraceLong(e, self); + oldOnError.call(o, e); + }; - observer.onError = function (err) { - makeStackTraceLong(err, self); - oldOnError(err); - }; + return subscribe.call(self, o); + }; + } - return subscribe.call(self, observer); - }; + function Observable(subscribe) { + if (Rx.config.longStackSupport && hasStacks) { + var e = tryCatch(thrower)(new Error()).e; + this.stack = e.stack.substring(e.stack.indexOf('\n') + 1); + this._subscribe = makeSubscribe(this, subscribe); } else { this._subscribe = subscribe; } @@ -2111,16 +2107,25 @@ module.exports = Cycle; observableProto = Observable.prototype; /** - * Subscribes an observer to the observable sequence. - * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * Determines whether the given object is an Observable + * @param {Any} An object to determine whether it is an Observable + * @returns {Boolean} true if an Observable, else false. + */ + Observable.isObservable = function (o) { + return o && isFunction(o.subscribe); + } + + /** + * Subscribes an o to the observable sequence. + * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ - observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { - return this._subscribe(typeof observerOrOnNext === 'object' ? - observerOrOnNext : - observerCreate(observerOrOnNext, onError, onCompleted)); + observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) { + return this._subscribe(typeof oOrOnNext === 'object' ? + oOrOnNext : + observerCreate(oOrOnNext, onError, onCompleted)); }; /** @@ -2155,7 +2160,7 @@ module.exports = Cycle; return Observable; })(); - + var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); @@ -2193,7 +2198,71 @@ module.exports = Cycle; return ObservableBase; }(Observable)); - + +var FlatMapObservable = (function(__super__){ + + inherits(FlatMapObservable, __super__); + + function FlatMapObservable(source, selector, resultSelector, thisArg) { + this.resultSelector = Rx.helpers.isFunction(resultSelector) ? + resultSelector : null; + + this.selector = Rx.internals.bindCallback(Rx.helpers.isFunction(selector) ? selector : function() { return selector; }, thisArg, 3); + this.source = source; + + __super__.call(this); + + } + + FlatMapObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this)); + }; + + function InnerObserver(observer, selector, resultSelector, source) { + this.i = 0; + this.selector = selector; + this.resultSelector = resultSelector; + this.source = source; + this.isStopped = false; + this.o = observer; + } + + InnerObserver.prototype._wrapResult = function(result, x, i) { + return this.resultSelector ? + result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) : + result; + }; + + InnerObserver.prototype.onNext = function(x) { + + if (this.isStopped) return; + + var i = this.i++; + var result = tryCatch(this.selector)(x, i, this.source); + + if (result === errorObj) { + return this.o.onError(result.e); + } + + Rx.helpers.isPromise(result) && (result = Rx.Observable.fromPromise(result)); + (Rx.helpers.isArrayLike(result) || Rx.helpers.isIterable(result)) && (result = Rx.Observable.from(result)); + + this.o.onNext(this._wrapResult(result, x, i)); + + }; + + InnerObserver.prototype.onError = function(e) { + if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) {this.isStopped = true; this.o.onCompleted(); } + }; + + return FlatMapObservable; + +}(ObservableBase)); + var Enumerable = Rx.internals.Enumerable = function () { }; var ConcatEnumerableObservable = (function(__super__) { @@ -2417,7 +2486,7 @@ module.exports = Cycle; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { return new OfEnumerable(source, selector, thisArg); }; - + /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * @@ -2433,7 +2502,7 @@ module.exports = Cycle; return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; - + /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. @@ -2455,33 +2524,33 @@ module.exports = Cycle; return d; }, source); }; - - var FromPromiseObservable = (function(__super__) { - inherits(FromPromiseObservable, __super__); - function FromPromiseObservable(p) { - this.p = p; - __super__.call(this); - } - - FromPromiseObservable.prototype.subscribeCore = function(o) { - this.p.then(function (data) { - o.onNext(data); - o.onCompleted(); - }, function (err) { o.onError(err); }); - return disposableEmpty; - }; - - return FromPromiseObservable; - }(ObservableBase)); - - /** - * Converts a Promise to an Observable sequence - * @param {Promise} An ES6 Compliant promise. - * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. - */ - var observableFromPromise = Observable.fromPromise = function (promise) { - return new FromPromiseObservable(promise); - }; + + var FromPromiseObservable = (function(__super__) { + inherits(FromPromiseObservable, __super__); + function FromPromiseObservable(p) { + this.p = p; + __super__.call(this); + } + + FromPromiseObservable.prototype.subscribeCore = function(o) { + this.p.then(function (data) { + o.onNext(data); + o.onCompleted(); + }, function (err) { o.onError(err); }); + return disposableEmpty; + }; + + return FromPromiseObservable; + }(ObservableBase)); + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new FromPromiseObservable(promise); + }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example @@ -2508,7 +2577,7 @@ module.exports = Cycle; }); }); }; - + var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { @@ -2560,7 +2629,7 @@ module.exports = Cycle; observableProto.toArray = function () { return new ToArrayObservable(this); }; - + /** * Creates an observable sequence from a specified subscribe method implementation. * @example @@ -2570,10 +2639,10 @@ module.exports = Cycle; * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ - Observable.create = Observable.createWithDisposable = function (subscribe, parent) { + Observable.create = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; - + /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * @@ -2594,7 +2663,7 @@ module.exports = Cycle; return result.subscribe(observer); }); }; - + var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { @@ -2603,26 +2672,29 @@ module.exports = Cycle; } EmptyObservable.prototype.subscribeCore = function (observer) { - var sink = new EmptySink(observer, this); + var sink = new EmptySink(observer, this.scheduler); return sink.run(); }; - function EmptySink(observer, parent) { + function EmptySink(observer, scheduler) { this.observer = observer; - this.parent = parent; + this.scheduler = scheduler; } function scheduleItem(s, state) { state.onCompleted(); + return disposableEmpty; } EmptySink.prototype.run = function () { - return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); + return this.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); + var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler); + /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * @@ -2634,9 +2706,9 @@ module.exports = Cycle; */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); - return new EmptyObservable(scheduler); + return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler); }; - + var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { @@ -2646,8 +2718,8 @@ module.exports = Cycle; __super__.call(this); } - FromObservable.prototype.subscribeCore = function (observer) { - var sink = new FromSink(observer, this); + FromObservable.prototype.subscribeCore = function (o) { + var sink = new FromSink(o, this); return sink.run(); }; @@ -2655,38 +2727,30 @@ module.exports = Cycle; }(ObservableBase)); var FromSink = (function () { - function FromSink(observer, parent) { - this.observer = observer; + function FromSink(o, parent) { + this.o = o; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), - observer = this.observer, + o = this.o, mapper = this.parent.mapper; function loopRecursive(i, recurse) { - try { - var next = it.next(); - } catch (e) { - return observer.onError(e); - } - if (next.done) { - return observer.onCompleted(); - } + var next = tryCatch(it.next).call(it); + if (next === errorObj) { return o.onError(next.e); } + if (next.done) { return o.onCompleted(); } var result = next.value; - if (mapper) { - try { - result = mapper(result, i); - } catch (e) { - return observer.onError(e); - } + if (isFunction(mapper)) { + result = tryCatch(mapper)(result, i); + if (result === errorObj) { return o.onError(result.e); } } - observer.onNext(result); + o.onNext(result); recurse(i + 1); } @@ -2698,7 +2762,7 @@ module.exports = Cycle; var maxSafeInteger = Math.pow(2, 53) - 1; - function StringIterable(str) { + function StringIterable(s) { this._s = s; } @@ -2706,7 +2770,7 @@ module.exports = Cycle; return new StringIterator(this._s); }; - function StringIterator(str) { + function StringIterator(s) { this._s = s; this._l = s.length; this._i = 0; @@ -2801,7 +2865,7 @@ module.exports = Cycle; isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } - + var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { @@ -2836,7 +2900,7 @@ module.exports = Cycle; return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; - + /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of @@ -2847,7 +2911,7 @@ module.exports = Cycle; isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; - + /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * @@ -2887,7 +2951,7 @@ module.exports = Cycle; }); }); }; - + function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); @@ -2913,7 +2977,7 @@ module.exports = Cycle; for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; - + /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. @@ -2936,7 +3000,7 @@ module.exports = Cycle; }; }); }; - + /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. @@ -2959,7 +3023,7 @@ module.exports = Cycle; }; }); }; - + var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { @@ -2973,14 +3037,16 @@ module.exports = Cycle; return NeverObservable; }(ObservableBase)); + var NEVER_OBSERVABLE = new NeverObservable(); + /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { - return new NeverObservable(); + return NEVER_OBSERVABLE; }; - + var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { @@ -3028,7 +3094,7 @@ module.exports = Cycle; scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; - + var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { @@ -3080,7 +3146,7 @@ module.exports = Cycle; isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; - + var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { @@ -3128,7 +3194,7 @@ module.exports = Cycle; isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; - + var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { @@ -3138,23 +3204,28 @@ module.exports = Cycle; } JustObservable.prototype.subscribeCore = function (observer) { - var sink = new JustSink(observer, this); + var sink = new JustSink(observer, this.value, this.scheduler); return sink.run(); }; - function JustSink(observer, parent) { + function JustSink(observer, value, scheduler) { this.observer = observer; - this.parent = parent; + this.value = value; + this.scheduler = scheduler; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); + return disposableEmpty; } JustSink.prototype.run = function () { - return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); + var state = [this.value, this.observer]; + return this.scheduler === immediateScheduler ? + scheduleItem(null, state) : + this.scheduler.scheduleWithState(state, scheduleItem); }; return JustObservable; @@ -3167,11 +3238,11 @@ module.exports = Cycle; * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ - var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { + var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; - + var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { @@ -3209,11 +3280,11 @@ module.exports = Cycle; * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ - var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) { + var observableThrow = Observable['throw'] = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; - + /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. @@ -3221,19 +3292,21 @@ module.exports = Cycle; * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { - return new AnonymousObservable(function (observer) { - var disposable = disposableEmpty, resource, source; - try { - resource = resourceFactory(); - resource && (disposable = resource); - source = observableFactory(resource); - } catch (exception) { - return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); + return new AnonymousObservable(function (o) { + var disposable = disposableEmpty; + var resource = tryCatch(resourceFactory)(); + if (resource === errorObj) { + return new CompositeDisposable(observableThrow(resource.e).subscribe(o), disposable); + } + resource && (disposable = resource); + var source = tryCatch(observableFactory)(resource); + if (source === errorObj) { + return new CompositeDisposable(observableThrow(source.e).subscribe(o), disposable); } - return new CompositeDisposable(source.subscribe(observer), disposable); + return new CompositeDisposable(source.subscribe(o), disposable); }); }; - + /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. @@ -3263,106 +3336,122 @@ module.exports = Cycle; } } - leftSubscription.setDisposable(leftSource.subscribe(function (left) { - choiceL(); - choice === leftChoice && observer.onNext(left); - }, function (err) { - choiceL(); - choice === leftChoice && observer.onError(err); - }, function () { - choiceL(); - choice === leftChoice && observer.onCompleted(); - })); + var leftSubscribe = observerCreate( + function (left) { + choiceL(); + choice === leftChoice && observer.onNext(left); + }, + function (e) { + choiceL(); + choice === leftChoice && observer.onError(e); + }, + function () { + choiceL(); + choice === leftChoice && observer.onCompleted(); + } + ); + var rightSubscribe = observerCreate( + function (right) { + choiceR(); + choice === rightChoice && observer.onNext(right); + }, + function (e) { + choiceR(); + choice === rightChoice && observer.onError(e); + }, + function () { + choiceR(); + choice === rightChoice && observer.onCompleted(); + } + ); - rightSubscription.setDisposable(rightSource.subscribe(function (right) { - choiceR(); - choice === rightChoice && observer.onNext(right); - }, function (err) { - choiceR(); - choice === rightChoice && observer.onError(err); - }, function () { - choiceR(); - choice === rightChoice && observer.onCompleted(); - })); + leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe)); + rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe)); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; - + + function amb(p, c) { return p.amb(c); } + /** * Propagates the observable sequence or Promise that reacts first. - * - * @example - * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { - var acc = observableNever(), items = []; + var acc = observableNever(), items; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { - for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } - } - - function func(previous, current) { - return previous.amb(current); + var len = arguments.length; + items = new Array(items); + for(var i = 0; i < len; i++) { items[i] = arguments[i]; } } for (var i = 0, len = items.length; i < len; i++) { - acc = func(acc, items[i]); + acc = amb(acc, items[i]); } return acc; }; - - function observableCatchHandler(source, handler) { - return new AnonymousObservable(function (o) { - var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); - subscription.setDisposable(d1); - d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { - try { - var result = handler(e); - } catch (ex) { - return o.onError(ex); - } - isPromise(result) && (result = observableFromPromise(result)); - var d = new SingleAssignmentDisposable(); - subscription.setDisposable(d); - d.setDisposable(result.subscribe(o)); - }, function (x) { o.onCompleted(x); })); + var CatchObserver = (function(__super__) { + inherits(CatchObserver, __super__); + function CatchObserver(o, s, fn) { + this._o = o; + this._s = s; + this._fn = fn; + __super__.call(this); + } + + CatchObserver.prototype.next = function (x) { this._o.onNext(x); }; + CatchObserver.prototype.completed = function () { return this._o.onCompleted(); }; + CatchObserver.prototype.error = function (e) { + var result = tryCatch(this._fn)(e); + if (result === errorObj) { return this._o.onError(result.e); } + isPromise(result) && (result = observableFromPromise(result)); + + var d = new SingleAssignmentDisposable(); + this._s.setDisposable(d); + d.setDisposable(result.subscribe(this._o)); + }; + return CatchObserver; + }(AbstractObserver)); + + function observableCatchHandler(source, handler) { + return new AnonymousObservable(function (o) { + var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); + subscription.setDisposable(d1); + d1.setDisposable(source.subscribe(new CatchObserver(o, subscription, handler))); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. - * @example - * 1 - xs.catchException(ys) - * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ - observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { - return typeof handlerOrSecond === 'function' ? - observableCatchHandler(this, handlerOrSecond) : - observableCatch([this, handlerOrSecond]); + observableProto['catch'] = function (handlerOrSecond) { + return isFunction(handlerOrSecond) ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; - + /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ - var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { - var items = []; + var observableCatch = Observable['catch'] = function () { + var items; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { - for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } + var len = arguments.length; + items = new Array(len); + for(var i = 0; i < len; i++) { items[i] = arguments[i]; } } return enumerableOf(items).catchError(); }; - + /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. @@ -3382,7 +3471,7 @@ module.exports = Cycle; } return combineLatest.apply(this, args); }; - + /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * @@ -3443,7 +3532,7 @@ module.exports = Cycle; return new CompositeDisposable(subscriptions); }, this); }; - + /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. @@ -3453,77 +3542,77 @@ module.exports = Cycle; args.unshift(this); return observableConcat.apply(null, args); }; - - var ConcatObservable = (function(__super__) { - inherits(ConcatObservable, __super__); - function ConcatObservable(sources) { - this.sources = sources; - __super__.call(this); - } - - ConcatObservable.prototype.subscribeCore = function(o) { - var sink = new ConcatSink(this.sources, o); - return sink.run(); - }; - - function ConcatSink(sources, o) { - this.sources = sources; - this.o = o; - } - ConcatSink.prototype.run = function () { - var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; - var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { - if (isDisposed) { return; } - if (i === length) { - return o.onCompleted(); - } - - // Check if promise - var currentValue = sources[i]; - isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); - - var d = new SingleAssignmentDisposable(); - subscription.setDisposable(d); - d.setDisposable(currentValue.subscribe( - function (x) { o.onNext(x); }, - function (e) { o.onError(e); }, - function () { self(i + 1); } - )); - }); - - return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { - isDisposed = true; - })); - }; - - - return ConcatObservable; - }(ObservableBase)); - - /** - * Concatenates all the observable sequences. - * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. - * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. - */ - var observableConcat = Observable.concat = function () { - var args; - if (Array.isArray(arguments[0])) { - args = arguments[0]; - } else { - args = new Array(arguments.length); - for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } - } - return new ConcatObservable(args); - }; - + + var ConcatObservable = (function(__super__) { + inherits(ConcatObservable, __super__); + function ConcatObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + ConcatObservable.prototype.subscribeCore = function(o) { + var sink = new ConcatSink(this.sources, o); + return sink.run(); + }; + + function ConcatSink(sources, o) { + this.sources = sources; + this.o = o; + } + ConcatSink.prototype.run = function () { + var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; + var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { + if (isDisposed) { return; } + if (i === length) { + return o.onCompleted(); + } + + // Check if promise + var currentValue = sources[i]; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + function (x) { o.onNext(x); }, + function (e) { o.onError(e); }, + function () { self(i + 1); } + )); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + + return ConcatObservable; + }(ObservableBase)); + + /** + * Concatenates all the observable sequences. + * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. + * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. + */ + var observableConcat = Observable.concat = function () { + var args; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + } else { + args = new Array(arguments.length); + for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } + } + return new ConcatObservable(args); + }; + /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ - observableProto.concatAll = observableProto.concatObservable = function () { + observableProto.concatAll = function () { return this.merge(1); }; - + var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); @@ -3650,7 +3739,7 @@ module.exports = Cycle; observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; - + /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. @@ -3673,7 +3762,7 @@ module.exports = Cycle; } return observableOf(scheduler, sources).mergeAll(); }; - + var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); @@ -3688,7 +3777,7 @@ module.exports = Cycle; m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; - + function MergeAllObserver(o, g) { this.o = o; this.g = g; @@ -3702,7 +3791,7 @@ module.exports = Cycle; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); - sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); + sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { @@ -3728,9 +3817,8 @@ module.exports = Cycle; return false; }; - function InnerObserver(parent, g, sad) { + function InnerObserver(parent, sad) { this.parent = parent; - this.g = g; this.sad = sad; this.isStopped = false; } @@ -3767,10 +3855,10 @@ module.exports = Cycle; * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ - observableProto.mergeAll = observableProto.mergeObservable = function () { + observableProto.mergeAll = function () { return new MergeAllObservable(this); }; - + var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; @@ -3851,7 +3939,7 @@ module.exports = Cycle; return group; }); }; - + /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. @@ -3861,7 +3949,7 @@ module.exports = Cycle; if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; - + /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @@ -3894,7 +3982,7 @@ module.exports = Cycle; return new CompositeDisposable(subscription, cancelable); }); }; - + /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. @@ -3924,7 +4012,7 @@ module.exports = Cycle; return disposables; }, source); }; - + var SwitchObservable = (function(__super__) { inherits(SwitchObservable, __super__); function SwitchObservable(source) { @@ -4020,7 +4108,7 @@ module.exports = Cycle; observableProto['switch'] = observableProto.switchLatest = function () { return new SwitchObservable(this); }; - + var TakeUntilObservable = (function(__super__) { inherits(TakeUntilObservable, __super__); @@ -4075,7 +4163,7 @@ module.exports = Cycle; observableProto.takeUntil = function (other) { return new TakeUntilObservable(this, other); }; - + function falseFactory() { return false; } /** @@ -4123,7 +4211,7 @@ module.exports = Cycle; return new CompositeDisposable(subscriptions); }, this); }; - + function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (o) { @@ -4186,7 +4274,7 @@ module.exports = Cycle; return new CompositeDisposable(subscriptions); }, parent); }; - + /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. @@ -4199,7 +4287,7 @@ module.exports = Cycle; var first = args.shift(); return first.zip.apply(first, args); }; - + function falseFactory() { return false; } function arrayFactory() { return []; } @@ -4244,37 +4332,35 @@ module.exports = Cycle; return new CompositeDisposable(subscriptions); }); }; - + + function asObservable(source) { + return function subscribe(o) { return source.subscribe(o); }; + } + /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { - var source = this; - return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); + return new AnonymousObservable(asObservable(this), this); }; - + + function toArray(x) { return x.toArray(); } + function notEmpty(x) { return x.length > 0; } + /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. - * - * @example - * var res = xs.bufferWithCount(10); - * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { - if (typeof skip !== 'number') { - skip = count; - } - return this.windowWithCount(count, skip).selectMany(function (x) { - return x.toArray(); - }).where(function (x) { - return x.length > 0; - }); + typeof skip !== 'number' && (skip = count); + return this.windowWithCount(count, skip) + .flatMap(toArray) + .filter(notEmpty); }; - + /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. @@ -4285,59 +4371,102 @@ module.exports = Cycle; return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; - + + var DistinctUntilChangedObservable = (function(__super__) { + inherits(DistinctUntilChangedObservable, __super__); + function DistinctUntilChangedObservable(source, keyFn, comparer) { + this.source = source; + this.keyFn = keyFn; + this.comparer = comparer; + __super__.call(this); + } + + DistinctUntilChangedObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer)); + }; + + return DistinctUntilChangedObservable; + }(ObservableBase)); + + function DistinctUntilChangedObserver(o, keyFn, comparer) { + this.o = o; + this.keyFn = keyFn; + this.comparer = comparer; + this.hasCurrentKey = false; + this.currentKey = null; + this.isStopped = false; + } + + DistinctUntilChangedObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + var key = x; + if (isFunction(this.keyFn)) { + key = tryCatch(this.keyFn)(x); + if (key === errorObj) { return this.o.onError(key.e); } + } + if (this.hasCurrentKey) { + comparerEquals = tryCatch(this.comparer)(this.currentKey, key); + if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); } + } + if (!this.hasCurrentKey || !comparerEquals) { + this.hasCurrentKey = true; + this.currentKey = key; + this.o.onNext(x); + } + }; + DistinctUntilChangedObserver.prototype.onError = function(e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + DistinctUntilChangedObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.o.onCompleted(); + } + }; + DistinctUntilChangedObserver.prototype.dispose = function() { this.isStopped = true; }; + DistinctUntilChangedObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + /** - * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - * - * var obs = observable.distinctUntilChanged(); - * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); - * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); - * - * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. - * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. - * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. - */ - observableProto.distinctUntilChanged = function (keySelector, comparer) { - var source = this; + * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer. + * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keyFn, comparer) { comparer || (comparer = defaultComparer); - return new AnonymousObservable(function (o) { - var hasCurrentKey = false, currentKey; - return source.subscribe(function (value) { - var key = value; - if (keySelector) { - key = tryCatch(keySelector)(value); - if (key === errorObj) { return o.onError(key.e); } - } - if (hasCurrentKey) { - var comparerEquals = tryCatch(comparer)(currentKey, key); - if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } - } - if (!hasCurrentKey || !comparerEquals) { - hasCurrentKey = true; - currentKey = key; - o.onNext(value); - } - }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); - }, this); + return new DistinctUntilChangedObservable(this, keyFn, comparer); }; - + var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; - this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? - observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : - observerOrOnNext; + this._oN = observerOrOnNext; + this._oE = onError; + this._oC = onCompleted; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { - return this.source.subscribe(new InnerObserver(o, this.t)); + return this.source.subscribe(new InnerObserver(o, this)); }; - function InnerObserver(o, t) { + function InnerObserver(o, p) { this.o = o; - this.t = t; + this.t = !p._oN || isFunction(p._oN) ? + observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) : + p._oN; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { @@ -4419,42 +4548,28 @@ module.exports = Cycle; observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; - + /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ - observableProto['finally'] = observableProto.ensure = function (action) { + observableProto['finally'] = function (action) { var source = this; return new AnonymousObservable(function (observer) { - var subscription; - try { - subscription = source.subscribe(observer); - } catch (e) { + var subscription = tryCatch(source.subscribe).call(source, observer); + if (subscription === errorObj) { action(); - throw e; + return thrower(subscription.e); } return disposableCreate(function () { - try { - subscription.dispose(); - } catch (e) { - throw e; - } finally { - action(); - } + var r = tryCatch(subscription.dispose).call(subscription); + action(); + r === errorObj && thrower(r.e); }); }, this); }; - /** - * @deprecated use #finally or #ensure instead. - */ - observableProto.finallyAction = function (action) { - //deprecate('finallyAction', 'finally or ensure'); - return this.ensure(action); - }; - var IgnoreElementsObservable = (function(__super__) { inherits(IgnoreElementsObservable, __super__); @@ -4505,7 +4620,7 @@ module.exports = Cycle; observableProto.ignoreElements = function () { return new IgnoreElementsObservable(this); }; - + /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. @@ -4524,7 +4639,7 @@ module.exports = Cycle; }); }, source); }; - + /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. @@ -4533,7 +4648,7 @@ module.exports = Cycle; observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; - + /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); @@ -4547,7 +4662,7 @@ module.exports = Cycle; observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; - + /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. @@ -4560,7 +4675,7 @@ module.exports = Cycle; */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); - }; + }; var ScanObservable = (function(__super__) { inherits(ScanObservable, __super__); function ScanObservable(source, accumulator, hasSeed, seed) { @@ -4571,15 +4686,15 @@ module.exports = Cycle; __super__.call(this); } - ScanObservable.prototype.subscribeCore = function(observer) { - return this.source.subscribe(new ScanObserver(observer,this)); + ScanObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o,this)); }; return ScanObservable; }(ObservableBase)); - function ScanObserver(observer, parent) { - this.observer = observer; + function InnerObserver(o, parent) { + this.o = o; this.accumulator = parent.accumulator; this.hasSeed = parent.hasSeed; this.seed = parent.seed; @@ -4588,42 +4703,41 @@ module.exports = Cycle; this.hasValue = false; this.isStopped = false; } - ScanObserver.prototype.onNext = function (x) { - if (this.isStopped) { return; } - !this.hasValue && (this.hasValue = true); - try { + InnerObserver.prototype = { + onNext: function (x) { + if (this.isStopped) { return; } + !this.hasValue && (this.hasValue = true); if (this.hasAccumulation) { - this.accumulation = this.accumulator(this.accumulation, x); + this.accumulation = tryCatch(this.accumulator)(this.accumulation, x); } else { - this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; + this.accumulation = this.hasSeed ? tryCatch(this.accumulator)(this.seed, x) : x; this.hasAccumulation = true; } - } catch (e) { - return this.observer.onError(e); - } - this.observer.onNext(this.accumulation); - }; - ScanObserver.prototype.onError = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.observer.onError(e); - } - }; - ScanObserver.prototype.onCompleted = function () { - if (!this.isStopped) { - this.isStopped = true; - !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); - this.observer.onCompleted(); - } - }; - ScanObserver.prototype.dispose = function() { this.isStopped = true; }; - ScanObserver.prototype.fail = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.observer.onError(e); - return true; + if (this.accumulation === errorObj) { return this.o.onError(this.accumulation.e); } + this.o.onNext(this.accumulation); + }, + onError: function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }, + onCompleted: function () { + if (!this.isStopped) { + this.isStopped = true; + !this.hasValue && this.hasSeed && this.o.onNext(this.seed); + this.o.onCompleted(); + } + }, + dispose: function() { this.isStopped = true; }, + fail: function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; } - return false; }; /** @@ -4634,17 +4748,14 @@ module.exports = Cycle; * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { - var hasSeed = false, seed, accumulator, source = this; + var hasSeed = false, seed, accumulator = arguments[0]; if (arguments.length === 2) { hasSeed = true; - seed = arguments[0]; - accumulator = arguments[1]; - } else { - accumulator = arguments[0]; + seed = arguments[1]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; - + /** * Bypasses a specified number of elements at the end of an observable sequence. * @description @@ -4664,7 +4775,7 @@ module.exports = Cycle; }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; - + /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example @@ -4684,7 +4795,7 @@ module.exports = Cycle; for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; - + /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description @@ -4707,7 +4818,7 @@ module.exports = Cycle; }); }, source); }; - + /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * @@ -4730,7 +4841,7 @@ module.exports = Cycle; }); }, source); }; - + /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * @@ -4783,7 +4894,7 @@ module.exports = Cycle; return refCountDisposable; }, source); }; - + function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { @@ -4829,7 +4940,7 @@ module.exports = Cycle; concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; - + /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. @@ -4883,7 +4994,7 @@ module.exports = Cycle; }); }, this).concatAll(); }; - + /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * @@ -4910,7 +5021,7 @@ module.exports = Cycle; }); }, source); }; - + // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { @@ -4962,7 +5073,7 @@ module.exports = Cycle; function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; - + /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * @@ -4972,13 +5083,12 @@ module.exports = Cycle; * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. - * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ - observableProto.groupBy = function (keySelector, elementSelector, comparer) { - return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + observableProto.groupBy = function (keySelector, elementSelector) { + return this.groupByUntil(keySelector, elementSelector, observableNever); }; - + /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same @@ -4990,93 +5100,82 @@ module.exports = Cycle; * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. - * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ - observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) { var source = this; - elementSelector || (elementSelector = identity); - comparer || (comparer = defaultComparer); - return new AnonymousObservable(function (observer) { - function handleError(e) { return function (item) { item.onError(e); }; } - var map = new Dictionary(0, comparer), + return new AnonymousObservable(function (o) { + var map = new Map(), groupDisposable = new CompositeDisposable(), - refCountDisposable = new RefCountDisposable(groupDisposable); - - groupDisposable.add(source.subscribe(function (x) { - var key; - try { - key = keySelector(x); - } catch (e) { - map.getValues().forEach(handleError(e)); - observer.onError(e); - return; - } - - var fireNewMapEntry = false, - writer = map.tryGetValue(key); - if (!writer) { - writer = new Subject(); - map.set(key, writer); - fireNewMapEntry = true; - } - - if (fireNewMapEntry) { - var group = new GroupedObservable(key, writer, refCountDisposable), - durationGroup = new GroupedObservable(key, writer); - try { - duration = durationSelector(durationGroup); - } catch (e) { - map.getValues().forEach(handleError(e)); - observer.onError(e); - return; + refCountDisposable = new RefCountDisposable(groupDisposable), + handleError = function (e) { return function (item) { item.onError(e); }; }; + + groupDisposable.add( + source.subscribe(function (x) { + var key = tryCatch(keySelector)(x); + if (key === errorObj) { + map.forEach(handleError(key.e)); + return o.onError(key.e); } - observer.onNext(group); - - var md = new SingleAssignmentDisposable(); - groupDisposable.add(md); + var fireNewMapEntry = false, writer = map.get(key); + if (writer === undefined) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } - var expire = function () { - map.remove(key) && writer.onCompleted(); - groupDisposable.remove(md); - }; + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + var duration = tryCatch(durationSelector)(durationGroup); + if (duration === errorObj) { + map.forEach(handleError(duration.e)); + return o.onError(duration.e); + } - md.setDisposable(duration.take(1).subscribe( - noop, - function (exn) { - map.getValues().forEach(handleError(exn)); - observer.onError(exn); - }, - expire) - ); - } + o.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + map.forEach(handleError(e)); + o.onError(e); + }, + function () { + if (map['delete'](key)) { writer.onCompleted(); } + groupDisposable.remove(md); + })); + } - var element; - try { - element = elementSelector(x); - } catch (e) { - map.getValues().forEach(handleError(e)); - observer.onError(e); - return; - } + var element = x; + if (isFunction(elementSelector)) { + element = tryCatch(elementSelector)(x); + if (element === errorObj) { + map.forEach(handleError(element.e)); + return o.onError(element.e); + } + } - writer.onNext(element); - }, function (ex) { - map.getValues().forEach(handleError(ex)); - observer.onError(ex); - }, function () { - map.getValues().forEach(function (item) { item.onCompleted(); }); - observer.onCompleted(); - })); + writer.onNext(element); + }, function (e) { + map.forEach(handleError(e)); + o.onError(e); + }, function () { + map.forEach(function (item) { item.onCompleted(); }); + o.onCompleted(); + })); return refCountDisposable; }, source); }; - + var MapObservable = (function (__super__) { inherits(MapObservable, __super__); @@ -5085,7 +5184,7 @@ module.exports = Cycle; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } - + function innerMap(selector, self) { return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } } @@ -5097,7 +5196,7 @@ module.exports = Cycle; MapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; - + function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; @@ -5105,13 +5204,11 @@ module.exports = Cycle; this.i = 0; this.isStopped = false; } - + InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector)(x, this.i++, this.source); - if (result === errorObj) { - return this.o.onError(result.e); - } + if (result === errorObj) { return this.o.onError(result.e); } this.o.onNext(result); }; InnerObserver.prototype.onError = function (e) { @@ -5127,7 +5224,7 @@ module.exports = Cycle; this.o.onError(e); return true; } - + return false; }; @@ -5147,17 +5244,9 @@ module.exports = Cycle; this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; - - /** - * Retrieves the value of a specified nested property from all elements in - * the Observable sequence. - * @param {Arguments} arguments The nested properties to pluck. - * @returns {Observable} Returns a new Observable sequence of property values. - */ - observableProto.pluck = function () { - var args = arguments, len = arguments.length; - if (len === 0) { throw new Error('List of properties cannot be empty.'); } - return this.map(function (x) { + + function plucker(args, len) { + return function mapper(x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; @@ -5168,55 +5257,33 @@ module.exports = Cycle; } } return currentProp; - }); - }; - - function flatMap(source, selector, thisArg) { - var selectorFunc = bindCallback(selector, thisArg, 3); - return source.map(function (x, i) { - var result = selectorFunc(x, i, source); - isPromise(result) && (result = observableFromPromise(result)); - (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); - return result; - }).mergeAll(); + } } /** - * One of the Following: - * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - * - * @example - * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); - * Or: - * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. - * - * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); - * Or: - * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. - * - * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); - * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. - * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. - * @param {Any} [thisArg] Object to use as this when executing callback. - * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + * Retrieves the value of a specified nested property from all elements in + * the Observable sequence. + * @param {Arguments} arguments The nested properties to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. */ - observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { - if (isFunction(selector) && isFunction(resultSelector)) { - return this.flatMap(function (x, i) { - var selectorResult = selector(x, i); - isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); - (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); - - return selectorResult.map(function (y, i2) { - return resultSelector(x, y, i, i2); - }); - }, thisArg); - } - return isFunction(selector) ? - flatMap(this, selector, thisArg) : - flatMap(this, function () { return selector; }); + observableProto.pluck = function () { + var len = arguments.length, args = new Array(len); + if (len === 0) { throw new Error('List of properties cannot be empty.'); } + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return this.map(plucker(args, len)); }; - + +observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) { + return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll(); +}; + + +// +//Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit, selector, resultSelector, thisArg) { +// return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit); +//}; +// + /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. @@ -5268,19 +5335,10 @@ module.exports = Cycle; }); }, source).mergeAll(); }; - - /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then - * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. - * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. - * @param {Any} [thisArg] Object to use as this when executing callback. - * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences - * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. - */ - observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { - return this.select(selector, thisArg).switchLatest(); - }; - + +Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) { + return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest(); +}; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { @@ -5334,7 +5392,7 @@ module.exports = Cycle; observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipObservable(this, count); - }; + }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. @@ -5363,7 +5421,7 @@ module.exports = Cycle; }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; - + /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * @@ -5387,7 +5445,7 @@ module.exports = Cycle; }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; - + /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. @@ -5417,7 +5475,7 @@ module.exports = Cycle; }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; - + var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); @@ -5485,7 +5543,7 @@ module.exports = Cycle; return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; - + function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; @@ -5520,56 +5578,12 @@ module.exports = Cycle; }); }, source); } - + function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } - - /** - * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. - * For aggregation behavior with incremental intermediate results, see Observable.scan. - * @deprecated Use #reduce instead - * @param {Mixed} [seed] The initial accumulator value. - * @param {Function} accumulator An accumulator function to be invoked on each element. - * @returns {Observable} An observable sequence containing a single element with the final accumulator value. - */ - observableProto.aggregate = function () { - var hasSeed = false, accumulator, seed, source = this; - if (arguments.length === 2) { - hasSeed = true; - seed = arguments[0]; - accumulator = arguments[1]; - } else { - accumulator = arguments[0]; - } - return new AnonymousObservable(function (o) { - var hasAccumulation, accumulation, hasValue; - return source.subscribe ( - function (x) { - !hasValue && (hasValue = true); - try { - if (hasAccumulation) { - accumulation = accumulator(accumulation, x); - } else { - accumulation = hasSeed ? accumulator(seed, x) : x; - hasAccumulation = true; - } - } catch (e) { - return o.onError(e); - } - }, - function (e) { o.onError(e); }, - function () { - hasValue && o.onNext(accumulation); - !hasValue && hasSeed && o.onNext(seed); - !hasValue && !hasSeed && o.onError(new EmptyError()); - o.onCompleted(); - } - ); - }, source); - }; - + var ReduceObservable = (function(__super__) { inherits(ReduceObservable, __super__); function ReduceObservable(source, acc, hasSeed, seed) { @@ -5645,41 +5659,106 @@ module.exports = Cycle; } return new ReduceObservable(this, accumulator, hasSeed, seed); }; - + + var SomeObserver = (function (__super__) { + inherits(SomeObserver, __super__); + + function SomeObserver(o, fn, s) { + this._o = o; + this._fn = fn; + this._s = s; + this._i = 0; + __super__.call(this); + } + + SomeObserver.prototype.next = function (x) { + var result = tryCatch(this._fn)(x, this._i++, this._s); + if (result === errorObj) { return this._o.onError(result.e); } + if (Boolean(result)) { + this._o.onNext(true); + this._o.onCompleted(); + } + }; + SomeObserver.prototype.error = function (e) { this._o.onError(e); }; + SomeObserver.prototype.completed = function () { + this._o.onNext(false); + this._o.onCompleted(); + }; + + return SomeObserver; + }(AbstractObserver)); + /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { - var source = this; - return predicate ? - source.filter(predicate, thisArg).some() : - new AnonymousObservable(function (observer) { - return source.subscribe(function () { - observer.onNext(true); - observer.onCompleted(); - }, function (e) { observer.onError(e); }, function () { - observer.onNext(false); - observer.onCompleted(); - }); - }, source); + var source = this, fn = bindCallback(predicate, thisArg, 3); + return new AnonymousObservable(function (o) { + return source.subscribe(new SomeObserver(o, fn, source)); + }); }; - /** @deprecated use #some instead */ - observableProto.any = function () { - //deprecate('any', 'some'); - return this.some.apply(this, arguments); - }; - + var IsEmptyObserver = (function(__super__) { + inherits(IsEmptyObserver, __super__); + function IsEmptyObserver(o) { + this._o = o; + __super__.call(this); + } + + IsEmptyObserver.prototype.next = function () { + this._o.onNext(false); + this._o.onCompleted(); + }; + IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); }; + IsEmptyObserver.prototype.completed = function () { + this._o.onNext(true); + this._o.onCompleted(); + }; + + return IsEmptyObserver; + }(AbstractObserver)); + /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { - return this.any().map(not); + var source = this; + return new AnonymousObservable(function (o) { + return source.subscribe(new IsEmptyObserver(o)); + }, source); }; - + + var EveryObserver = (function (__super__) { + inherits(EveryObserver, __super__); + + function EveryObserver(o, fn, s) { + this._o = o; + this._fn = fn; + this._s = s; + this._i = 0; + __super__.call(this); + } + + EveryObserver.prototype.next = function (x) { + var result = tryCatch(this._fn)(x, this._i++, this._s); + if (result === errorObj) { return this._o.onError(result.e); } + if (!Boolean(result)) { + this._o.onNext(false); + this._o.onCompleted(); + } + }; + EveryObserver.prototype.error = function (e) { this._o.onError(e); }; + EveryObserver.prototype.completed = function () { + this._o.onNext(true); + this._o.onCompleted(); + }; + + return EveryObserver; + }(AbstractObserver)); + /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. @@ -5687,15 +5766,12 @@ module.exports = Cycle; * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { - return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); + var source = this, fn = bindCallback(predicate, thisArg, 3); + return new AnonymousObservable(function (o) { + return source.subscribe(new EveryObserver(o, fn, source)); + }, this); }; - /** @deprecated use #every instead */ - observableProto.all = function () { - //deprecate('all', 'every'); - return this.every.apply(this, arguments); - }; - /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. @@ -5737,7 +5813,7 @@ module.exports = Cycle; //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; - + /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example @@ -5752,7 +5828,7 @@ module.exports = Cycle; this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; - + /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. @@ -5784,7 +5860,7 @@ module.exports = Cycle; }); }, source); }; - + /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. @@ -5796,7 +5872,7 @@ module.exports = Cycle; this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; - + /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example @@ -5810,7 +5886,7 @@ module.exports = Cycle; comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; - + /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example @@ -5822,7 +5898,7 @@ module.exports = Cycle; observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; - + /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example @@ -5836,7 +5912,7 @@ module.exports = Cycle; comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; - + /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example @@ -5848,7 +5924,38 @@ module.exports = Cycle; observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; - + + var AverageObserver = (function(__super__) { + inherits(AverageObserver, __super__); + function AverageObserver(o, fn, s) { + this._o = o; + this._fn = fn; + this._s = s; + this._c = 0; + this._t = 0; + __super__.call(this); + } + + AverageObserver.prototype.next = function (x) { + if(this._fn) { + var r = tryCatch(this._fn)(x, this._c++, this._s); + if (r === errorObj) { return this._o.onError(r.e); } + this._t += r; + } else { + this._c++; + this._t += x; + } + }; + AverageObserver.prototype.error = function (e) { this._o.onError(e); }; + AverageObserver.prototype.completed = function () { + if (this._c === 0) { return this._o.onError(new EmptyError()); } + this._o.onNext(this._t / this._c); + this._o.onCompleted(); + }; + + return AverageObserver; + }(AbstractObserver)); + /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. @@ -5856,19 +5963,15 @@ module.exports = Cycle; * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { - return keySelector && isFunction(keySelector) ? - this.map(keySelector, thisArg).average() : - this.reduce(function (prev, cur) { - return { - sum: prev.sum + cur, - count: prev.count + 1 - }; - }, {sum: 0, count: 0 }).map(function (s) { - if (s.count === 0) { throw new EmptyError(); } - return s.sum / s.count; - }); + var source = this, fn; + if (isFunction(keySelector)) { + fn = bindCallback(keySelector, thisArg, 3); + } + return new AnonymousObservable(function (o) { + return source.subscribe(new AverageObserver(o, fn, source)); + }, source); }; - + /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * @@ -5956,54 +6059,48 @@ module.exports = Cycle; return new CompositeDisposable(subscription1, subscription2); }, first); }; - - function elementAtOrDefault(source, index, hasDefault, defaultValue) { + + /** + * Returns the element at a specified index in a sequence or default value if not found. + * @param {Number} index The zero-based index of the element to retrieve. + * @param {Any} [defaultValue] The default value to use if elementAt does not find a value. + * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. + */ + observableProto.elementAt = function (index, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; return new AnonymousObservable(function (o) { var i = index; - return source.subscribe(function (x) { - if (i-- === 0) { - o.onNext(x); - o.onCompleted(); - } - }, function (e) { o.onError(e); }, function () { - if (!hasDefault) { - o.onError(new ArgumentOutOfRangeError()); - } else { - o.onNext(defaultValue); - o.onCompleted(); - } + return source.subscribe( + function (x) { + if (i-- === 0) { + o.onNext(x); + o.onCompleted(); + } + }, + function (e) { o.onError(e); }, + function () { + if (defaultValue === undefined) { + o.onError(new ArgumentOutOfRangeError()); + } else { + o.onNext(defaultValue); + o.onCompleted(); + } }); }, source); - } - - /** - * Returns the element at a specified index in a sequence. - * @example - * var res = source.elementAt(5); - * @param {Number} index The zero-based index of the element to retrieve. - * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. - */ - observableProto.elementAt = function (index) { - return elementAtOrDefault(this, index, false); }; - + /** - * Returns the element at a specified index in a sequence or a default value if the index is out of range. - * @example - * var res = source.elementAtOrDefault(5); - * var res = source.elementAtOrDefault(5, 0); - * @param {Number} index The zero-based index of the element to retrieve. - * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. - * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. + * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ - observableProto.elementAtOrDefault = function (index, defaultValue) { - return elementAtOrDefault(this, index, true, defaultValue); - }; - - function singleOrDefaultAsync(source, hasDefault, defaultValue) { + observableProto.single = function (predicate, thisArg) { + if (isFunction(predicate)) { return this.filter(predicate, thisArg).single(); } + var source = this; return new AnonymousObservable(function (o) { - var value = defaultValue, seenValue = false; + var value, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); @@ -6012,133 +6109,123 @@ module.exports = Cycle; seenValue = true; } }, function (e) { o.onError(e); }, function () { - if (!seenValue && !hasDefault) { - o.onError(new EmptyError()); - } else { - o.onNext(value); - o.onCompleted(); - } + o.onNext(value); + o.onCompleted(); }); }, source); - } - - /** - * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. - */ - observableProto.single = function (predicate, thisArg) { - return predicate && isFunction(predicate) ? - this.where(predicate, thisArg).single() : - singleOrDefaultAsync(this, false); - }; - - /** - * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. - * @example - * var res = res = source.singleOrDefault(); - * var res = res = source.singleOrDefault(function (x) { return x === 42; }); - * res = source.singleOrDefault(function (x) { return x === 42; }, 0); - * res = source.singleOrDefault(null, 0); - * @memberOf Observable# - * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. - * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { - return predicate && isFunction(predicate) ? - this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : - singleOrDefaultAsync(this, true, defaultValue); }; - - function firstOrDefaultAsync(source, hasDefault, defaultValue) { - return new AnonymousObservable(function (o) { - return source.subscribe(function (x) { - o.onNext(x); - o.onCompleted(); - }, function (e) { o.onError(e); }, function () { - if (!hasDefault) { - o.onError(new EmptyError()); - } else { - o.onNext(defaultValue); - o.onCompleted(); + + var FirstObserver = (function(__super__) { + inherits(FirstObserver, __super__); + function FirstObserver(o, obj, s) { + this._o = o; + this._obj = obj; + this._s = s; + this._i = 0; + __super__.call(this); + } + + FirstObserver.prototype.next = function (x) { + if (this._obj.predicate) { + var res = tryCatch(this._obj.predicate)(x, this._i++, this._s); + if (res === errorObj) { return this._o.onError(res.e); } + if (Boolean(res)) { + this._o.onNext(x); + this._o.onCompleted(); } - }); - }, source); - } - + } else if (!this._obj.predicate) { + this._o.onNext(x); + this._o.onCompleted(); + } + }; + FirstObserver.prototype.error = function (e) { this._o.onError(e); }; + FirstObserver.prototype.completed = function () { + if (this._obj.defaultValue === undefined) { + this._o.onError(new EmptyError()); + } else { + this._o.onNext(this._obj.defaultValue); + this._o.onCompleted(); + } + }; + + return FirstObserver; + }(AbstractObserver)); + /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. - * @example - * var res = res = source.first(); - * var res = res = source.first(function (x) { return x > 3; }); - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ - observableProto.first = function (predicate, thisArg) { - return predicate ? - this.where(predicate, thisArg).first() : - firstOrDefaultAsync(this, false); - }; - - /** - * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { - return predicate ? - this.where(predicate).firstOrDefault(null, defaultValue) : - firstOrDefaultAsync(this, true, defaultValue); - }; - - function lastOrDefaultAsync(source, hasDefault, defaultValue) { + observableProto.first = function () { + var obj = {}, source = this; + if (typeof arguments[0] === 'object') { + obj = arguments[0]; + } else { + obj = { + predicate: arguments[0], + thisArg: arguments[1], + defaultValue: arguments[2] + }; + } + if (isFunction (obj.predicate)) { + var fn = obj.predicate; + obj.predicate = bindCallback(fn, obj.thisArg, 3); + } return new AnonymousObservable(function (o) { - var value = defaultValue, seenValue = false; - return source.subscribe(function (x) { - value = x; - seenValue = true; - }, function (e) { o.onError(e); }, function () { - if (!seenValue && !hasDefault) { - o.onError(new EmptyError()); - } else { - o.onNext(value); - o.onCompleted(); - } - }); + return source.subscribe(new FirstObserver(o, obj, source)); }, source); - } - + }; + /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ - observableProto.last = function (predicate, thisArg) { - return predicate ? - this.where(predicate, thisArg).last() : - lastOrDefaultAsync(this, false); - }; - - /** - * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { - return predicate ? - this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : - lastOrDefaultAsync(this, true, defaultValue); + observableProto.last = function () { + var obj = {}, source = this; + if (typeof arguments[0] === 'object') { + obj = arguments[0]; + } else { + obj = { + predicate: arguments[0], + thisArg: arguments[1], + defaultValue: arguments[2] + }; + } + if (isFunction (obj.predicate)) { + var fn = obj.predicate; + obj.predicate = bindCallback(fn, obj.thisArg, 3); + } + return new AnonymousObservable(function (o) { + var value, seenValue = false, i = 0; + return source.subscribe( + function (x) { + if (obj.predicate) { + var res = tryCatch(obj.predicate)(x, i++, source); + if (res === errorObj) { return o.onError(res.e); } + if (res) { + seenValue = true; + value = x; + } + } else if (!obj.predicate) { + seenValue = true; + value = x; + } + }, + function (e) { o.onError(e); }, + function () { + if (seenValue) { + o.onNext(value); + o.onCompleted(); + } + else if (obj.defaultValue === undefined) { + o.onError(new EmptyError()); + } else { + o.onNext(obj.defaultValue); + o.onCompleted(); + } + }); + }, source); }; - + function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { @@ -6163,7 +6250,7 @@ module.exports = Cycle; }); }, source); } - + /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. @@ -6173,7 +6260,7 @@ module.exports = Cycle; observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; - + /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. @@ -6184,7 +6271,7 @@ module.exports = Cycle; observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; - + /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. @@ -6203,7 +6290,7 @@ module.exports = Cycle; }); }, source); }; - + /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. @@ -6244,201 +6331,132 @@ module.exports = Cycle; }); }, source); }; - - var fnString = 'function', - throwString = 'throw', - isObject = Rx.internals.isObject; - - function toThunk(obj, ctx) { - if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } - if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } - if (isGenerator(obj)) { return observableSpawn(obj); } - if (isObservable(obj)) { return observableToThunk(obj); } - if (isPromise(obj)) { return promiseToThunk(obj); } - if (typeof obj === fnString) { return obj; } - if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } - - return obj; - } - function objectToThunk(obj) { - var ctx = this; +var wrap = Observable.wrap = function (fn) { + createObservable.__generatorFunction__ = fn; + return createObservable; - return function (done) { - var keys = Object.keys(obj), - pending = keys.length, - results = new obj.constructor(), - finished; + function createObservable() { + return Observable.spawn.call(this, fn.apply(this, arguments)); + } +}; - if (!pending) { - timeoutScheduler.schedule(function () { done(null, results); }); - return; - } +var spawn = Observable.spawn = function () { + var gen = arguments[0], self = this, args = []; + for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } - for (var i = 0, len = keys.length; i < len; i++) { - run(obj[keys[i]], keys[i]); - } + return new AnonymousObservable(function (o) { + var g = new CompositeDisposable(); - function run(fn, key) { - if (finished) { return; } - try { - fn = toThunk(fn, ctx); + if (isFunction(gen)) { gen = gen.apply(self, args); } + if (!gen || !isFunction(gen.next)) { + o.onNext(gen); + return o.onCompleted(); + } - if (typeof fn !== fnString) { - results[key] = fn; - return --pending || done(null, results); - } + processGenerator(); - fn.call(ctx, function(err, res) { - if (finished) { return; } + function processGenerator(res) { + var ret = tryCatch(gen.next).call(gen, res); + if (ret === errorObj) { return o.onError(ret.e); } + next(ret); + } - if (err) { - finished = true; - return done(err); - } + function onError(err) { + var ret = tryCatch(gen.next).call(gen, err); + if (ret === errorObj) { return o.onError(ret.e); } + next(ret); + } - results[key] = res; - --pending || done(null, results); - }); - } catch (e) { - finished = true; - done(e); + function next(ret) { + if (ret.done) { + o.onNext(ret.value); + o.onCompleted(); + return; + } + var value = toObservable.call(self, ret.value); + if (Observable.isObservable(value)) { + g.add(value.subscribe(processGenerator, onError)); + } else { + onError(new TypeError('type not supported')); } } - } - } - function observableToThunk(observable) { - return function (fn) { - var value, hasValue = false; - observable.subscribe( - function (v) { - value = v; - hasValue = true; - }, - fn, - function () { - hasValue && fn(null, value); - }); - } + return g; + }); } - function promiseToThunk(promise) { - return function(fn) { - promise.then(function(res) { - fn(null, res); - }, fn); - } - } +function toObservable(obj) { + if (!obj) { return obj; } + if (Observable.isObservable(obj)) { return obj; } + if (isPromise(obj)) { return Observable.fromPromise(obj); } + if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); } + if (isFunction(obj)) { return thunkToObservable.call(this, obj); } + if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); } + if (isObject(obj)) {return objectToObservable.call(this, obj);} + return obj; +} - function isObservable(obj) { - return obj && typeof obj.subscribe === fnString; - } +function arrayToObservable (obj) { + return Observable.from(obj) + .flatMap(toObservable) + .toArray(); +} - function isGeneratorFunction(obj) { - return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; - } +function objectToObservable (obj) { + var results = new obj.constructor(), keys = Object.keys(obj), observables = []; + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + var observable = toObservable.call(this, obj[key]); - function isGenerator(obj) { - return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; + if(observable && Observable.isObservable(observable)) { + defer(observable, key); + } else { + results[key] = obj[key]; + } } - /* - * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. - * @param {Function} The spawning function. - * @returns {Function} a function which has a done continuation. - */ - var observableSpawn = Rx.spawn = function (fn) { - var isGenFun = isGeneratorFunction(fn); - - return function (done) { - var ctx = this, - gen = fn; - - if (isGenFun) { - for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } - var len = args.length, - hasCallback = len && typeof args[len - 1] === fnString; - - done = hasCallback ? args.pop() : handleError; - gen = fn.apply(this, args); - } else { - done = done || handleError; - } - - next(); - - function exit(err, res) { - timeoutScheduler.schedule(done.bind(ctx, err, res)); - } - - function next(err, res) { - var ret; - - // multiple args - if (arguments.length > 2) { - for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } - } - - if (err) { - try { - ret = gen[throwString](err); - } catch (e) { - return exit(e); - } - } - - if (!err) { - try { - ret = gen.next(res); - } catch (e) { - return exit(e); - } - } - - if (ret.done) { - return exit(null, ret.value); - } + return Observable.forkJoin.apply(Observable, observables).map(function() { + return results; + }); - ret.value = toThunk(ret.value, ctx); - if (typeof ret.value === fnString) { - var called = false; - try { - ret.value.call(ctx, function() { - if (called) { - return; - } + function defer (observable, key) { + results[key] = undefined; + observables.push(observable.map(function (next) { + results[key] = next; + })); + } +} - called = true; - next.apply(ctx, arguments); - }); - } catch (e) { - timeoutScheduler.schedule(function () { - if (called) { - return; - } +function thunkToObservable(fn) { + var self = this; + return new AnonymousObservable(function (o) { + fn.call(self, function () { + var err = arguments[0], res = arguments[1]; + if (err) { return o.onError(err); } + if (arguments.length > 2) { + var args = []; + for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } + res = args; + } + o.onNext(res); + o.onCompleted(); + }); + }); +} - called = true; - next.call(ctx, e); - }); - } - return; - } +function isGenerator(obj) { + return isFunction (obj.next) && isFunction (obj.throw); +} - // Not supported - next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); - } - } - }; +function isGeneratorFunction(obj) { + var ctor = obj.constructor; + if (!ctor) { return false; } + if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; } + return isGenerator(ctor.prototype); +} - function handleError(err) { - if (!err) { return; } - timeoutScheduler.schedule(function() { - throw err; - }); - } - /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * @@ -6459,7 +6477,7 @@ module.exports = Cycle; Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; - + /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. @@ -6487,117 +6505,129 @@ module.exports = Cycle; return subject.asObservable(); }; }; - - /** - * Converts a callback function to an observable sequence. - * - * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. - * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. - * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. - */ - Observable.fromCallback = function (func, context, selector) { - return function () { - var len = arguments.length, args = new Array(len) - for(var i = 0; i < len; i++) { args[i] = arguments[i]; } - return new AnonymousObservable(function (observer) { - function handler() { - var len = arguments.length, results = new Array(len); - for(var i = 0; i < len; i++) { results[i] = arguments[i]; } +function createCbObservable(fn, ctx, selector, args) { + var o = new AsyncSubject(); - if (selector) { - try { - results = selector.apply(context, results); - } catch (e) { - return observer.onError(e); - } + args.push(createCbHandler(o, ctx, selector)); + fn.apply(ctx, args); - observer.onNext(results); - } else { - if (results.length <= 1) { - observer.onNext.apply(observer, results); - } else { - observer.onNext(results); - } - } + return o.asObservable(); +} - observer.onCompleted(); - } +function createCbHandler(o, ctx, selector) { + return function handler () { + var len = arguments.length, results = new Array(len); + for(var i = 0; i < len; i++) { results[i] = arguments[i]; } - args.push(handler); - func.apply(context, args); - }).publishLast().refCount(); - }; + if (isFunction(selector)) { + results = tryCatch(selector).apply(ctx, results); + if (results === errorObj) { return o.onError(results.e); } + o.onNext(results); + } else { + if (results.length <= 1) { + o.onNext(results[0]); + } else { + o.onNext(results); + } + } + + o.onCompleted(); }; - - /** - * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. - * @param {Function} func The function to call - * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. - * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. - */ - Observable.fromNodeCallback = function (func, context, selector) { - return function () { - var len = arguments.length, args = new Array(len); - for(var i = 0; i < len; i++) { args[i] = arguments[i]; } +} - return new AnonymousObservable(function (observer) { - function handler(err) { - if (err) { - observer.onError(err); - return; - } +/** + * Converts a callback function to an observable sequence. + * + * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence. + * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. + * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. + */ +Observable.fromCallback = function (fn, ctx, selector) { + return function () { + typeof ctx === 'undefined' && (ctx = this); - var len = arguments.length, results = []; - for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } + var len = arguments.length, args = new Array(len) + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return createCbObservable(fn, ctx, selector, args); + }; +}; - if (selector) { - try { - results = selector.apply(context, results); - } catch (e) { - return observer.onError(e); - } - observer.onNext(results); - } else { - if (results.length <= 1) { - observer.onNext.apply(observer, results); - } else { - observer.onNext(results); - } - } +function createNodeObservable(fn, ctx, selector, args) { + var o = new AsyncSubject(); + + args.push(createNodeHandler(o, ctx, selector)); + fn.apply(ctx, args); + + return o.asObservable(); +} - observer.onCompleted(); - } +function createNodeHandler(o, ctx, selector) { + return function handler () { + var err = arguments[0]; + if (err) { return o.onError(err); } - args.push(handler); - func.apply(context, args); - }).publishLast().refCount(); - }; - }; - - function createListener (element, name, handler) { - if (element.addEventListener) { - element.addEventListener(name, handler, false); - return disposableCreate(function () { - element.removeEventListener(name, handler, false); - }); + var len = arguments.length, results = []; + for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } + + if (isFunction(selector)) { + var results = tryCatch(selector).apply(ctx, results); + if (results === errorObj) { return o.onError(results.e); } + o.onNext(results); + } else { + if (results.length <= 1) { + o.onNext(results[0]); + } else { + o.onNext(results); + } } - throw new Error('No listener found'); + + o.onCompleted(); + }; +} + +/** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} fn The function to call + * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. + * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. + */ +Observable.fromNodeCallback = function (fn, ctx, selector) { + return function () { + typeof ctx === 'undefined' && (ctx = this); + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return createNodeObservable(fn, ctx, selector, args); + }; +}; + + function ListenDisposable(e, n, fn) { + this._e = e; + this._n = n; + this._fn = fn; + this._e.addEventListener(this._n, this._fn, false); + this.isDisposed = false; } + ListenDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this._e.removeEventListener(this._n, this._fn, false); + this.isDisposed = true; + } + }; function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList or HTMLCollection - var toStr = Object.prototype.toString; - if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') { + var elemToString = Object.prototype.toString.call(el); + if (elemToString === '[object NodeList]' || elemToString === '[object HTMLCollection]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { - disposables.add(createListener(el, eventName, handler)); + disposables.add(new ListenDisposable(el, eventName, handler)); } return disposables; @@ -6608,12 +6638,19 @@ module.exports = Cycle; */ Rx.config.useNativeEvents = false; + function eventHandler(o, selector) { + return function handler () { + var results = arguments[0]; + if (isFunction(selector)) { + results = tryCatch(selector).apply(null, arguments); + if (results === errorObj) { return o.onError(results.e); } + } + o.onNext(results); + }; + } + /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. - * - * @example - * var source = Rx.Observable.fromEvent(element, 'mouseup'); - * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. @@ -6638,56 +6675,42 @@ module.exports = Cycle; selector); } } - return new AnonymousObservable(function (observer) { + + return new AnonymousObservable(function (o) { return createEventListener( element, eventName, - function handler (e) { - var results = e; - - if (selector) { - try { - results = selector(arguments); - } catch (err) { - return observer.onError(err); - } - } - - observer.onNext(results); - }); + eventHandler(o, selector)); }).publish().refCount(); }; - + /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @param {Scheduler} [scheduler] A scheduler used to schedule the remove handler. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ - var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { - return new AnonymousObservable(function (observer) { - function innerHandler (e) { - var result = e; - if (selector) { - try { - result = selector(arguments); - } catch (err) { - return observer.onError(err); - } + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (o) { + function innerHandler () { + var result = arguments[0]; + if (isFunction(selector)) { + result = tryCatch(selector).apply(null, arguments); + if (result === errorObj) { return o.onError(result.e); } } - observer.onNext(result); + o.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { - if (removeHandler) { - removeHandler(innerHandler, returnValue); - } + isFunction(removeHandler) && removeHandler(innerHandler, returnValue); }); }).publish().refCount(); }; - + /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. @@ -6702,7 +6725,7 @@ module.exports = Cycle; } return observableFromPromise(promise); } - + var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); @@ -6760,7 +6783,7 @@ module.exports = Cycle; observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; - + function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], @@ -6770,7 +6793,7 @@ module.exports = Cycle; err; function next(x, i) { - values[i] = x + values[i] = x; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { return o.onError(err); } @@ -6822,7 +6845,7 @@ module.exports = Cycle; var subscription = combineLatestSource( this.source, - this.pauser.distinctUntilChanged().startWith(false), + this.pauser.startWith(false).distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) @@ -6891,146 +6914,149 @@ module.exports = Cycle; observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; - - var ControlledObservable = (function (__super__) { - - inherits(ControlledObservable, __super__); - - function subscribe (observer) { - return this.source.subscribe(observer); - } - function ControlledObservable (source, enableQueue, scheduler) { - __super__.call(this, subscribe, source); - this.subject = new ControlledSubject(enableQueue, scheduler); - this.source = source.multicast(this.subject).refCount(); - } +var ControlledObservable = (function (__super__) { - ControlledObservable.prototype.request = function (numberOfItems) { - return this.subject.request(numberOfItems == null ? -1 : numberOfItems); - }; + inherits(ControlledObservable, __super__); - return ControlledObservable; + function subscribe (observer) { + return this.source.subscribe(observer); + } - }(Observable)); + function ControlledObservable (source, enableQueue, scheduler) { + __super__.call(this, subscribe, source); + this.subject = new ControlledSubject(enableQueue, scheduler); + this.source = source.multicast(this.subject).refCount(); + } - var ControlledSubject = (function (__super__) { + ControlledObservable.prototype.request = function (numberOfItems) { + return this.subject.request(numberOfItems == null ? -1 : numberOfItems); + }; - function subscribe (observer) { - return this.subject.subscribe(observer); - } + return ControlledObservable; - inherits(ControlledSubject, __super__); +}(Observable)); - function ControlledSubject(enableQueue, scheduler) { - enableQueue == null && (enableQueue = true); +var ControlledSubject = (function (__super__) { - __super__.call(this, subscribe); - this.subject = new Subject(); - this.enableQueue = enableQueue; - this.queue = enableQueue ? [] : null; - this.requestedCount = 0; - this.requestedDisposable = disposableEmpty; - this.error = null; - this.hasFailed = false; - this.hasCompleted = false; - this.scheduler = scheduler || currentThreadScheduler; - } + function subscribe (observer) { + return this.subject.subscribe(observer); + } - addProperties(ControlledSubject.prototype, Observer, { - onCompleted: function () { - this.hasCompleted = true; - if (!this.enableQueue || this.queue.length === 0) { - this.subject.onCompleted(); - } else { - this.queue.push(Notification.createOnCompleted()); - } - }, - onError: function (error) { - this.hasFailed = true; - this.error = error; - if (!this.enableQueue || this.queue.length === 0) { - this.subject.onError(error); - } else { - this.queue.push(Notification.createOnError(error)); - } - }, - onNext: function (value) { - var hasRequested = false; + inherits(ControlledSubject, __super__); + + function ControlledSubject(enableQueue, scheduler) { + enableQueue == null && (enableQueue = true); + + __super__.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = null; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.scheduler = scheduler || currentThreadScheduler; + } - if (this.requestedCount === 0) { - this.enableQueue && this.queue.push(Notification.createOnNext(value)); - } else { - (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); - hasRequested = true; - } - hasRequested && this.subject.onNext(value); - }, - _processRequest: function (numberOfItems) { - if (this.enableQueue) { - while ((this.queue.length >= numberOfItems && numberOfItems > 0) || - (this.queue.length > 0 && this.queue[0].kind !== 'N')) { - var first = this.queue.shift(); - first.accept(this.subject); - if (first.kind === 'N') { - numberOfItems--; - } else { - this.disposeCurrentRequest(); - this.queue = []; - } + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + this.hasCompleted = true; + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + this.disposeCurrentRequest() + } else { + this.queue.push(Notification.createOnCompleted()); + } + }, + onError: function (error) { + this.hasFailed = true; + this.error = error; + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + this.disposeCurrentRequest() + } else { + this.queue.push(Notification.createOnError(error)); + } + }, + onNext: function (value) { + if (this.requestedCount <= 0) { + this.enableQueue && this.queue.push(Notification.createOnNext(value)); + } else { + (this.requestedCount-- === 0) && this.disposeCurrentRequest(); + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) { + var first = this.queue.shift(); + first.accept(this.subject); + if (first.kind === 'N') { + numberOfItems--; + } else { + this.disposeCurrentRequest(); + this.queue = []; } - - return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } + } - return { numberOfItems: numberOfItems, returnValue: false }; - }, - request: function (number) { - this.disposeCurrentRequest(); - var self = this; + return numberOfItems; + }, + request: function (number) { + this.disposeCurrentRequest(); + var self = this; - this.requestedDisposable = this.scheduler.scheduleWithState(number, - function(s, i) { - var r = self._processRequest(i), remaining = r.numberOfItems; - if (!r.returnValue) { - self.requestedCount = remaining; - self.requestedDisposable = disposableCreate(function () { - self.requestedCount = 0; - }); - } - }); + this.requestedDisposable = this.scheduler.scheduleWithState(number, + function(s, i) { + var remaining = self._processRequest(i); + var stopped = self.hasCompleted || self.hasFailed + if (!stopped && remaining > 0) { + self.requestedCount = remaining; - return this.requestedDisposable; - }, - disposeCurrentRequest: function () { + return disposableCreate(function () { + self.requestedCount = 0; + }); + // Scheduled item is still in progress. Return a new + // disposable to allow the request to be interrupted + // via dispose. + } + }); + + return this.requestedDisposable; + }, + disposeCurrentRequest: function () { + if (this.requestedDisposable) { this.requestedDisposable.dispose(); - this.requestedDisposable = disposableEmpty; + this.requestedDisposable = null; } - }); + } + }); - return ControlledSubject; - }(Observable)); + return ControlledSubject; +}(Observable)); - /** - * Attaches a controller to the observable sequence with the ability to queue. - * @example - * var source = Rx.Observable.interval(100).controlled(); - * source.request(3); // Reads 3 values - * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request - * @param {Scheduler} scheduler determines how the requests will be scheduled - * @returns {Observable} The observable sequence which only propagates values on request. - */ - observableProto.controlled = function (enableQueue, scheduler) { +/** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request + * @param {Scheduler} scheduler determines how the requests will be scheduled + * @returns {Observable} The observable sequence which only propagates values on request. + */ +observableProto.controlled = function (enableQueue, scheduler) { - if (enableQueue && isScheduler(enableQueue)) { - scheduler = enableQueue; - enableQueue = true; - } + if (enableQueue && isScheduler(enableQueue)) { + scheduler = enableQueue; + enableQueue = true; + } + + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue, scheduler); +}; - if (enableQueue == null) { enableQueue = true; } - return new ControlledObservable(this, enableQueue, scheduler); - }; - var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { @@ -7104,7 +7130,7 @@ module.exports = Cycle; ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; - + var WindowedObservable = (function (__super__) { function subscribe (observer) { @@ -7184,7 +7210,7 @@ module.exports = Cycle; ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; - + /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. @@ -7216,7 +7242,7 @@ module.exports = Cycle; return dest; }; - + /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's @@ -7243,7 +7269,7 @@ module.exports = Cycle; }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; - + /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. @@ -7260,7 +7286,7 @@ module.exports = Cycle; this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; - + /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. @@ -7269,7 +7295,7 @@ module.exports = Cycle; observableProto.share = function () { return this.publish().refCount(); }; - + /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. @@ -7286,7 +7312,7 @@ module.exports = Cycle; this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; - + /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. @@ -7306,7 +7332,7 @@ module.exports = Cycle; }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; - + /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. @@ -7316,7 +7342,7 @@ module.exports = Cycle; observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; - + /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. @@ -7338,7 +7364,7 @@ module.exports = Cycle; this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; - + /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. @@ -7357,7 +7383,7 @@ module.exports = Cycle; observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; - + var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; @@ -7370,7 +7396,7 @@ module.exports = Cycle; this.observer = null; } }; - + /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. @@ -7481,7 +7507,7 @@ module.exports = Cycle; return BehaviorSubject; }(Observable)); - + /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. @@ -7618,7 +7644,7 @@ module.exports = Cycle; return ReplaySubject; }(Observable)); - + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); @@ -7655,7 +7681,7 @@ module.exports = Cycle; return ConnectableObservable; }(Observable)); - + /** * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) @@ -7676,255 +7702,7 @@ module.exports = Cycle; return getObservable().subscribe(o); }); }; - - var Dictionary = (function () { - - var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], - noSuchkey = "no such key", - duplicatekey = "duplicate key"; - - function isPrime(candidate) { - if ((candidate & 1) === 0) { return candidate === 2; } - var num1 = Math.sqrt(candidate), - num2 = 3; - while (num2 <= num1) { - if (candidate % num2 === 0) { return false; } - num2 += 2; - } - return true; - } - - function getPrime(min) { - var index, num, candidate; - for (index = 0; index < primes.length; ++index) { - num = primes[index]; - if (num >= min) { return num; } - } - candidate = min | 1; - while (candidate < primes[primes.length - 1]) { - if (isPrime(candidate)) { return candidate; } - candidate += 2; - } - return min; - } - - function stringHashFn(str) { - var hash = 757602046; - if (!str.length) { return hash; } - for (var i = 0, len = str.length; i < len; i++) { - var character = str.charCodeAt(i); - hash = ((hash << 5) - hash) + character; - hash = hash & hash; - } - return hash; - } - - function numberHashFn(key) { - var c2 = 0x27d4eb2d; - key = (key ^ 61) ^ (key >>> 16); - key = key + (key << 3); - key = key ^ (key >>> 4); - key = key * c2; - key = key ^ (key >>> 15); - return key; - } - - var getHashCode = (function () { - var uniqueIdCounter = 0; - - return function (obj) { - if (obj == null) { throw new Error(noSuchkey); } - - // Check for built-ins before tacking on our own for any object - if (typeof obj === 'string') { return stringHashFn(obj); } - if (typeof obj === 'number') { return numberHashFn(obj); } - if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } - if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } - if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } - if (typeof obj.valueOf === 'function') { - // Hack check for valueOf - var valueOf = obj.valueOf(); - if (typeof valueOf === 'number') { return numberHashFn(valueOf); } - if (typeof valueOf === 'string') { return stringHashFn(valueOf); } - } - if (obj.hashCode) { return obj.hashCode(); } - - var id = 17 * uniqueIdCounter++; - obj.hashCode = function () { return id; }; - return id; - }; - }()); - - function newEntry() { - return { key: null, value: null, next: 0, hashCode: 0 }; - } - - function Dictionary(capacity, comparer) { - if (capacity < 0) { throw new ArgumentOutOfRangeError(); } - if (capacity > 0) { this._initialize(capacity); } - - this.comparer = comparer || defaultComparer; - this.freeCount = 0; - this.size = 0; - this.freeList = -1; - } - - var dictionaryProto = Dictionary.prototype; - - dictionaryProto._initialize = function (capacity) { - var prime = getPrime(capacity), i; - this.buckets = new Array(prime); - this.entries = new Array(prime); - for (i = 0; i < prime; i++) { - this.buckets[i] = -1; - this.entries[i] = newEntry(); - } - this.freeList = -1; - }; - - dictionaryProto.add = function (key, value) { - this._insert(key, value, true); - }; - - dictionaryProto._insert = function (key, value, add) { - if (!this.buckets) { this._initialize(0); } - var index3, - num = getHashCode(key) & 2147483647, - index1 = num % this.buckets.length; - for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { - if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { - if (add) { throw new Error(duplicatekey); } - this.entries[index2].value = value; - return; - } - } - if (this.freeCount > 0) { - index3 = this.freeList; - this.freeList = this.entries[index3].next; - --this.freeCount; - } else { - if (this.size === this.entries.length) { - this._resize(); - index1 = num % this.buckets.length; - } - index3 = this.size; - ++this.size; - } - this.entries[index3].hashCode = num; - this.entries[index3].next = this.buckets[index1]; - this.entries[index3].key = key; - this.entries[index3].value = value; - this.buckets[index1] = index3; - }; - - dictionaryProto._resize = function () { - var prime = getPrime(this.size * 2), - numArray = new Array(prime); - for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } - var entryArray = new Array(prime); - for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } - for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } - for (var index1 = 0; index1 < this.size; ++index1) { - var index2 = entryArray[index1].hashCode % prime; - entryArray[index1].next = numArray[index2]; - numArray[index2] = index1; - } - this.buckets = numArray; - this.entries = entryArray; - }; - - dictionaryProto.remove = function (key) { - if (this.buckets) { - var num = getHashCode(key) & 2147483647, - index1 = num % this.buckets.length, - index2 = -1; - for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { - if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { - if (index2 < 0) { - this.buckets[index1] = this.entries[index3].next; - } else { - this.entries[index2].next = this.entries[index3].next; - } - this.entries[index3].hashCode = -1; - this.entries[index3].next = this.freeList; - this.entries[index3].key = null; - this.entries[index3].value = null; - this.freeList = index3; - ++this.freeCount; - return true; - } else { - index2 = index3; - } - } - } - return false; - }; - - dictionaryProto.clear = function () { - var index, len; - if (this.size <= 0) { return; } - for (index = 0, len = this.buckets.length; index < len; ++index) { - this.buckets[index] = -1; - } - for (index = 0; index < this.size; ++index) { - this.entries[index] = newEntry(); - } - this.freeList = -1; - this.size = 0; - }; - - dictionaryProto._findEntry = function (key) { - if (this.buckets) { - var num = getHashCode(key) & 2147483647; - for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { - if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { - return index; - } - } - } - return -1; - }; - - dictionaryProto.count = function () { - return this.size - this.freeCount; - }; - - dictionaryProto.tryGetValue = function (key) { - var entry = this._findEntry(key); - return entry >= 0 ? - this.entries[entry].value : - undefined; - }; - - dictionaryProto.getValues = function () { - var index = 0, results = []; - if (this.entries) { - for (var index1 = 0; index1 < this.size; index1++) { - if (this.entries[index1].hashCode >= 0) { - results[index++] = this.entries[index1].value; - } - } - } - return results; - }; - - dictionaryProto.get = function (key) { - var entry = this._findEntry(key); - if (entry >= 0) { return this.entries[entry].value; } - throw new Error(noSuchkey); - }; - - dictionaryProto.set = function (key, value) { - this._insert(key, value, false); - }; - - dictionaryProto.containskey = function (key) { - return this._findEntry(key) >= 0; - }; - return Dictionary; - }()); - /** * Correlates the elements of two sequences based on overlapping durations. * @@ -7936,99 +7714,78 @@ module.exports = Cycle; */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; - return new AnonymousObservable(function (observer) { + return new AnonymousObservable(function (o) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; - var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftMap = new Map(), rightMap = new Map(); + var handleError = function (e) { o.onError(e); }; group.add(left.subscribe( function (value) { - var id = leftId++; - var md = new SingleAssignmentDisposable(); + var id = leftId++, md = new SingleAssignmentDisposable(); - leftMap.add(id, value); + leftMap.set(id, value); group.add(md); - var expire = function () { - leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); - group.remove(md); - }; - - var duration; - try { - duration = leftDurationSelector(value); - } catch (e) { - observer.onError(e); - return; - } - - md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + var duration = tryCatch(leftDurationSelector)(value); + if (duration === errorObj) { return o.onError(duration.e); } - rightMap.getValues().forEach(function (v) { - var result; - try { - result = resultSelector(value, v); - } catch (exn) { - observer.onError(exn); - return; - } + md.setDisposable(duration.take(1).subscribe( + noop, + handleError, + function () { + leftMap['delete'](id) && leftMap.size === 0 && leftDone && o.onCompleted(); + group.remove(md); + })); - observer.onNext(result); + rightMap.forEach(function (v) { + var result = tryCatch(resultSelector)(value, v); + if (result === errorObj) { return o.onError(result.e); } + o.onNext(result); }); }, - observer.onError.bind(observer), + handleError, function () { leftDone = true; - (rightDone || leftMap.count() === 0) && observer.onCompleted(); + (rightDone || leftMap.size === 0) && o.onCompleted(); }) ); group.add(right.subscribe( function (value) { - var id = rightId++; - var md = new SingleAssignmentDisposable(); + var id = rightId++, md = new SingleAssignmentDisposable(); - rightMap.add(id, value); + rightMap.set(id, value); group.add(md); - var expire = function () { - rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); - group.remove(md); - }; - - var duration; - try { - duration = rightDurationSelector(value); - } catch (e) { - observer.onError(e); - return; - } - - md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + var duration = tryCatch(rightDurationSelector)(value); + if (duration === errorObj) { return o.onError(duration.e); } - leftMap.getValues().forEach(function (v) { - var result; - try { - result = resultSelector(v, value); - } catch (exn) { - observer.onError(exn); - return; - } + md.setDisposable(duration.take(1).subscribe( + noop, + handleError, + function () { + rightMap['delete'](id) && rightMap.size === 0 && rightDone && o.onCompleted(); + group.remove(md); + })); - observer.onNext(result); + leftMap.forEach(function (v) { + var result = tryCatch(resultSelector)(v, value); + if (result === errorObj) { return o.onError(result.e); } + o.onNext(result); }); }, - observer.onError.bind(observer), + handleError, function () { rightDone = true; - (leftDone || rightMap.count() === 0) && observer.onCompleted(); + (leftDone || rightMap.size === 0) && o.onCompleted(); }) ); return group; }, left); }; - + /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * @@ -8040,118 +7797,107 @@ module.exports = Cycle; */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; - return new AnonymousObservable(function (observer) { + return new AnonymousObservable(function (o) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); - var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftMap = new Map(), rightMap = new Map(); var leftId = 0, rightId = 0; + var handleError = function (e) { return function (v) { v.onError(e); }; }; - function handleError(e) { return function (v) { v.onError(e); }; }; + function handleError(e) { }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; - leftMap.add(id, s); + leftMap.set(id, s); - var result; - try { - result = resultSelector(value, addRef(s, r)); - } catch (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); - return; + var result = tryCatch(resultSelector)(value, addRef(s, r)); + if (result === errorObj) { + leftMap.forEach(handleError(result.e)); + return o.onError(result.e); } - observer.onNext(result); + o.onNext(result); - rightMap.getValues().forEach(function (v) { s.onNext(v); }); + rightMap.forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); - var expire = function () { - leftMap.remove(id) && s.onCompleted(); - group.remove(md); - }; - - var duration; - try { - duration = leftDurationSelector(value); - } catch (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); - return; + var duration = tryCatch(leftDurationSelector)(value); + if (duration === errorObj) { + leftMap.forEach(handleError(duration.e)); + return o.onError(duration.e); } md.setDisposable(duration.take(1).subscribe( noop, function (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); + leftMap.forEach(handleError(e)); + o.onError(e); }, - expire) - ); + function () { + leftMap['delete'](id) && s.onCompleted(); + group.remove(md); + })); }, function (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); + leftMap.forEach(handleError(e)); + o.onError(e); }, - observer.onCompleted.bind(observer)) + function () { o.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; - rightMap.add(id, value); + rightMap.set(id, value); var md = new SingleAssignmentDisposable(); group.add(md); - var expire = function () { - rightMap.remove(id); - group.remove(md); - }; - - var duration; - try { - duration = rightDurationSelector(value); - } catch (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); - return; + var duration = tryCatch(rightDurationSelector)(value); + if (duration === errorObj) { + leftMap.forEach(handleError(duration.e)); + return o.onError(duration.e); } + md.setDisposable(duration.take(1).subscribe( noop, function (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); + leftMap.forEach(handleError(e)); + o.onError(e); }, - expire) - ); + function () { + rightMap['delete'](id); + group.remove(md); + })); - leftMap.getValues().forEach(function (v) { v.onNext(value); }); + leftMap.forEach(function (v) { v.onNext(value); }); }, function (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); + leftMap.forEach(handleError(e)); + o.onError(e); }) ); return r; }, left); }; - - /** - * Projects each element of an observable sequence into zero or more buffers. - * - * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). - * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. - * @returns {Observable} An observable sequence of windows. - */ - observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { - return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); - }; - + + function toArray(x) { return x.toArray(); } + + /** + * Projects each element of an observable sequence into zero or more buffers. + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function () { + return this.window.apply(this, arguments) + .flatMap(toArray); + }; + /** * Projects each element of an observable sequence into zero or more windows. * @@ -8257,7 +8003,7 @@ module.exports = Cycle; return r; }, source); } - + /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. @@ -8281,7 +8027,7 @@ module.exports = Cycle; observer.onCompleted.bind(observer)); }, source); }; - + /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. @@ -8301,7 +8047,7 @@ module.exports = Cycle; this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; - + var WhileEnumerable = (function(__super__) { inherits(WhileEnumerable, __super__); function WhileEnumerable(c, s) { @@ -8324,7 +8070,7 @@ module.exports = Cycle; function enumerableWhile(condition, source) { return new WhileEnumerable(condition, source); } - + /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. @@ -8335,9 +8081,9 @@ module.exports = Cycle; observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; - + /** - * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers y?1:x=rStartingLine&&lineNumber<=rEndingLine}function isNodeFrame(stackLine){return stackLine.indexOf("(module.js:")!==-1||stackLine.indexOf("(node.js:")!==-1}function captureLine(){if(!hasStacks){return}try{throw new Error}catch(e){var lines=e.stack.split("\n");var firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2];var fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber){return}rFileName=fileNameAndLineNumber[0];return fileNameAndLineNumber[1]}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1){return[attempt1[1],Number(attempt1[2])]}var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2){return[attempt2[1],Number(attempt2[2])]}var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3){return[attempt3[1],Number(attempt3[2])]}}var EmptyError=Rx.EmptyError=function(){this.message="Sequence contains no elements.";Error.call(this)};EmptyError.prototype=Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError=function(){this.message="Object has been disposed";Error.call(this)};ObjectDisposedError.prototype=Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError=function(){this.message="Argument out of range";Error.call(this)};ArgumentOutOfRangeError.prototype=Error.prototype;var NotSupportedError=Rx.NotSupportedError=function(message){this.message=message||"This operation is not supported";Error.call(this)};NotSupportedError.prototype=Error.prototype;var NotImplementedError=Rx.NotImplementedError=function(message){this.message=message||"This operation is not implemented";Error.call(this)};NotImplementedError.prototype=Error.prototype;var notImplemented=Rx.helpers.notImplemented=function(){throw new NotImplementedError};var notSupported=Rx.helpers.notSupported=function(){throw new NotSupportedError};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};var isIterable=Rx.helpers.isIterable=function(o){return o[$iterator$]!==undefined};var isArrayLike=Rx.helpers.isArrayLike=function(o){return o&&o.length!==undefined};Rx.helpers.iterator=$iterator$;var bindCallback=Rx.internals.bindCallback=function(func,thisArg,argCount){if(typeof thisArg==="undefined"){return func}switch(argCount){case 0:return function(){return func.call(thisArg)};case 1:return function(arg){return func.call(thisArg,arg)};case 2:return function(value,index){return func.call(thisArg,value,index)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)}}return function(){return func.apply(thisArg,arguments)}};var dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,supportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,stringProto=String.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{supportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){supportNodeClass=true}var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);var isObject=Rx.internals.isObject=function(value){var type=typeof value;return value&&(type=="function"||type=="object")||false};function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=dontEnumsLength;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index-1}})}}stackA.pop();stackB.pop();return result}var hasProp={}.hasOwnProperty,slice=Array.prototype.slice;var inherits=this.inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){for(var sources=[],i=1,len=arguments.length;i=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left0){var item=queue.dequeue();!item.isCancelled()&&item.invoke()}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue=new PriorityQueue(4);queue.enqueue(si);var result=tryCatch(runTrampoline)();queue=null;if(result===errorObj){return thrower(result.e)}}else{queue.enqueue(si)}return si.disposable}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired=function(){return!queue};return currentScheduler}();var scheduleMethod,clearMethod;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else if(!!root.WScript){localSetTimeout=function(fn,time){root.WScript.Sleep(time);fn()}}else{throw new NotSupportedError}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;clearMethod=function(handle){delete tasksByHandle[handle]};function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle)},0)}else{var task=tasksByHandle[handle];if(task){currentlyRunning=true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning=false;if(result===errorObj){return thrower(result.e)}}}}var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(isFunction(setImmediate)){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;setImmediate(function(){runTask(id)});return id}}else if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;process.nextTick(function(){runTask(id)});return id}}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random();function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length))}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else if(root.attachEvent){root.attachEvent("onmessage",onGlobalPostMessage)}else{root.onmessage=onGlobalPostMessage}scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;root.postMessage(MSG_PREFIX+currentId,"*");return id}}else if(!!root.MessageChannel){var channel=new root.MessageChannel;channel.port1.onmessage=function(e){runTask(e.data)};scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;channel.port2.postMessage(id);return id}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");var id=nextHandle++;tasksByHandle[id]=action;scriptElement.onreadystatechange=function(){runTask(id);scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement);return id}}else{scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;localSetTimeout(function(){runTask(id)},0);return id}}})();var timeoutScheduler=Scheduler.timeout=Scheduler["default"]=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime),disposable=new SingleAssignmentDisposable;if(dt===0){return scheduler.scheduleWithState(state,action)}var id=localSetTimeout(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(__super__){function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,__super__);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler; -this._recursiveOriginal=null;this._recursiveWrapper=null;__super__.call(this,this._scheduler.now.bind(this._scheduler),scheduleNow,scheduleRelative,scheduleAbsolute)}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind=kind;this.value=value;this.exception=exception;this._accept=accept;this._acceptObservable=acceptObservable;this.toString=toString}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var self=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){return new Notification("N",value,null,_accept,_acceptObservable,toString)}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(e){return new Notification("E",null,e,_accept,_acceptObservable,toString)}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){return new Notification("C",null,null,_accept,_acceptObservable,toString)}}();var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){return new AnonymousObserver(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){return new AnonymousObserver(function(x){return handler.call(thisArg,notificationCreateOnNext(x))},function(e){return handler.call(thisArg,notificationCreateOnError(e))},function(){return handler.call(thisArg,notificationCreateOnCompleted())})};Observer.prototype.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};Observer.prototype.makeSafe=function(disposable){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,disposable)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false;__super__.call(this)}AbstractObserver.prototype.next=notImplemented;AbstractObserver.prototype.error=notImplemented;AbstractObserver.prototype.completed=notImplemented;AbstractObserver.prototype.onNext=function(value){if(!this.isStopped){this.next(value)}};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(__super__){inherits(CheckedObserver,__super__);function CheckedObserver(observer){__super__.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();var res=tryCatch(this._observer.onNext).call(this._observer,value);this._state=0;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onError=function(err){this.checkAccess();var res=tryCatch(this._observer.onError).call(this._observer,err);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();var res=tryCatch(this._observer.onCompleted).call(this._observer);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(e){var self=this;this.queue.push(function(){self.observer.onError(e)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false,parent=this;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}try{work()}catch(ex){parent.queue=[];parent.hasFaulted=true;throw ex}self()}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(scheduler,observer,cancel){__super__.call(this,scheduler,observer);this._cancel=cancel}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};ObserveOnObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this._cancel&&this._cancel.dispose();this._cancel=null};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function Observable(subscribe){if(Rx.config.longStackSupport&&hasStacks){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var self=this;this._subscribe=function(observer){var oldOnError=observer.onError.bind(observer);observer.onError=function(err){makeStackTraceLong(err,self);oldOnError(err)};return subscribe.call(self,observer)}}else{this._subscribe=subscribe}}observableProto=Observable.prototype;observableProto.subscribe=observableProto.forEach=function(observerOrOnNext,onError,onCompleted){return this._subscribe(typeof observerOrOnNext==="object"?observerOrOnNext:observerCreate(observerOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();var ObservableBase=Rx.ObservableBase=function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function ObservableBase(){__super__.call(this,subscribe)}ObservableBase.prototype.subscribeCore=notImplemented;return ObservableBase}(Observable);var Enumerable=Rx.internals.Enumerable=function(){};var ConcatEnumerableObservable=function(__super__){inherits(ConcatEnumerableObservable,__super__);function ConcatEnumerableObservable(sources){this.sources=sources;__super__.call(this)}ConcatEnumerableObservable.prototype.subscribeCore=function(o){var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](),function(e,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(new InnerObserver(o,self,e)))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};function InnerObserver(o,s,e){this.o=o;this.s=s;this.e=e;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.o.onNext(x)}};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.s(this.e)}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err);return true}return false};return ConcatEnumerableObservable}(ObservableBase);Enumerable.prototype.concat=function(){return new ConcatEnumerableObservable(this)};var CatchErrorObservable=function(__super__){inherits(CatchErrorObservable,__super__);function CatchErrorObservable(sources){this.sources=sources;__super__.call(this)}CatchErrorObservable.prototype.subscribeCore=function(o){var e=this.sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return lastException!==null?o.onError(lastException):o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},self,function(){o.onCompleted()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};return CatchErrorObservable}(ObservableBase);Enumerable.prototype.catchError=function(){return new CatchErrorObservable(this)};Enumerable.prototype.catchErrorWhen=function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject,notifier=new Subject,handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){if(lastException){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable;var inner=new SingleAssignmentDisposable;subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex)},function(){o.onCompleted()}));exceptions.onNext(exn)},function(){o.onCompleted()}))});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var RepeatEnumerable=function(__super__){inherits(RepeatEnumerable,__super__);function RepeatEnumerable(v,c){this.v=v;this.c=c==null?-1:c}RepeatEnumerable.prototype[$iterator$]=function(){return new RepeatEnumerator(this)};function RepeatEnumerator(p){this.v=p.v;this.l=p.c}RepeatEnumerator.prototype.next=function(){if(this.l===0){return doneEnumerator}if(this.l>0){this.l--}return{done:false,value:this.v}};return RepeatEnumerable}(Enumerable);var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){return new RepeatEnumerable(value,repeatCount)};var OfEnumerable=function(__super__){inherits(OfEnumerable,__super__);function OfEnumerable(s,fn,thisArg){this.s=s;this.fn=fn?bindCallback(fn,thisArg,3):null}OfEnumerable.prototype[$iterator$]=function(){return new OfEnumerator(this)};function OfEnumerator(p){this.i=-1;this.s=p.s;this.l=this.s.length;this.fn=p.fn}OfEnumerator.prototype.next=function(){return++this.imaxSafeInteger){return maxSafeInteger}return len}var observableFrom=Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isFunction(mapFn)){throw new Error("mapFn when provided must be a function")}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2)}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler)};var FromArrayObservable=function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args=args;this.scheduler=scheduler;__super__.call(this)}FromArrayObservable.prototype.subscribeCore=function(observer){var sink=new FromArraySink(observer,this);return sink.run()};return FromArrayObservable}(ObservableBase);function FromArraySink(observer,parent){this.observer=observer;this.parent=parent}FromArraySink.prototype.run=function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i0){observer.onNext(value);i>0&&i--}if(i===0){return observer.onCompleted()}recurse(i)}return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,loopRecursive)};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RepeatObservable(value,repeatCount,scheduler)};var JustObservable=function(__super__){inherits(JustObservable,__super__);function JustObservable(value,scheduler){this.value=value;this.scheduler=scheduler;__super__.call(this)}JustObservable.prototype.subscribeCore=function(observer){var sink=new JustSink(observer,this);return sink.run()};function JustSink(observer,parent){this.observer=observer;this.parent=parent}function scheduleItem(s,state){var value=state[0],observer=state[1];observer.onNext(value);observer.onCompleted()}JustSink.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],scheduleItem)};return JustObservable}(ObservableBase);var observableReturn=Observable["return"]=Observable.just=Observable.returnValue=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new JustObservable(value,scheduler)};var ThrowObservable=function(__super__){inherits(ThrowObservable,__super__);function ThrowObservable(error,scheduler){this.error=error;this.scheduler=scheduler;__super__.call(this)}ThrowObservable.prototype.subscribeCore=function(o){var sink=new ThrowSink(o,this);return sink.run()};function ThrowSink(o,p){this.o=o;this.p=p}function scheduleItem(s,state){var e=state[0],o=state[1];o.onError(e)}ThrowSink.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],scheduleItem)};return ThrowObservable}(ObservableBase);var observableThrow=Observable["throw"]=Observable.throwError=Observable.throwException=function(error,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new ThrowObservable(error,scheduler)};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(observer){var disposable=disposableEmpty,resource,source;try{resource=resourceFactory();resource&&(disposable=resource);source=observableFactory(resource)}catch(exception){return new CompositeDisposable(observableThrow(exception).subscribe(observer),disposable)}return new CompositeDisposable(source.subscribe(observer),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}leftSubscription.setDisposable(leftSource.subscribe(function(left){choiceL();choice===leftChoice&&observer.onNext(left)},function(err){choiceL();choice===leftChoice&&observer.onError(err)},function(){choiceL();choice===leftChoice&&observer.onCompleted()}));rightSubscription.setDisposable(rightSource.subscribe(function(right){choiceR();choice===rightChoice&&observer.onNext(right)},function(err){choiceR();choice===rightChoice&&observer.onError(err)},function(){choiceR();choice===rightChoice&&observer.onCompleted()}));return new CompositeDisposable(leftSubscription,rightSubscription)})};Observable.amb=function(){var acc=observableNever(),items=[];if(Array.isArray(arguments[0])){items=arguments[0]}else{for(var i=0,len=arguments.length;i0){parent.handleSubscribe(parent.q.shift())}else{parent.activeCount--;parent.done&&parent.activeCount===0&&parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeObserver}();observableProto.merge=function(maxConcurrentOrOther){return typeof maxConcurrentOrOther!=="number"?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther)};var observableMerge=Observable.merge=function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler=immediateScheduler;for(i=1;i0})){var queuedValues=queues.map(function(x){return x.shift()}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},parent)};Observable.zip=function(){var len=arguments.length,args=new Array(len);for(var i=0;i0})){var res=queues.map(function(x){return x.shift()});o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){return o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}))})(idx)}return new CompositeDisposable(subscriptions)})};observableProto.asObservable=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(o)},source)};observableProto.bufferWithCount=function(count,skip){if(typeof skip!=="number"){skip=count}return this.windowWithCount(count,skip).selectMany(function(x){return x.toArray()}).where(function(x){return x.length>0})};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto.distinctUntilChanged=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var hasCurrentKey=false,currentKey;return source.subscribe(function(value){var key=value;if(keySelector){key=tryCatch(keySelector)(value);if(key===errorObj){return o.onError(key.e)}}if(hasCurrentKey){var comparerEquals=tryCatch(comparer)(currentKey,key);if(comparerEquals===errorObj){return o.onError(comparerEquals.e)}}if(!hasCurrentKey||!comparerEquals){hasCurrentKey=true;currentKey=key;o.onNext(value)}},function(e){o.onError(e)},function(){o.onCompleted()})},this)};var TapObservable=function(__super__){inherits(TapObservable,__super__);function TapObservable(source,observerOrOnNext,onError,onCompleted){this.source=source;this.t=!observerOrOnNext||isFunction(observerOrOnNext)?observerCreate(observerOrOnNext||noop,onError||noop,onCompleted||noop):observerOrOnNext;__super__.call(this)}TapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.t))};function InnerObserver(o,t){this.o=o;this.t=t;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var res=tryCatch(this.t.onNext).call(this.t,x);if(res===errorObj){this.o.onError(res.e)}this.o.onNext(x)};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onError).call(this.t,err);if(res===errorObj){return this.o.onError(res.e)}this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onCompleted).call(this.t);if(res===errorObj){return this.o.onError(res.e)}this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return TapObservable}(ObservableBase);observableProto["do"]=observableProto.tap=observableProto.doAction=function(observerOrOnNext,onError,onCompleted){return new TapObservable(this,observerOrOnNext,onError,onCompleted)};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=observableProto.ensure=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription;try{subscription=source.subscribe(observer)}catch(e){action();throw e}return disposableCreate(function(){try{subscription.dispose()}catch(e){throw e}finally{action()}})},this)};observableProto.finallyAction=function(action){return this.ensure(action)};var IgnoreElementsObservable=function(__super__){inherits(IgnoreElementsObservable,__super__);function IgnoreElementsObservable(source){this.source=source;__super__.call(this)}IgnoreElementsObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o))};function InnerObserver(o){this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=noop;InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};return IgnoreElementsObservable}(ObservableBase);observableProto.ignoreElements=function(){return new IgnoreElementsObservable(this)};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})},source)};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchError()};observableProto.retryWhen=function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier)};var ScanObservable=function(__super__){inherits(ScanObservable,__super__);function ScanObservable(source,accumulator,hasSeed,seed){this.source=source;this.accumulator=accumulator;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ScanObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new ScanObserver(observer,this))};return ScanObservable}(ObservableBase);function ScanObserver(observer,parent){this.observer=observer;this.accumulator=parent.accumulator;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.accumulation=null;this.hasValue=false;this.isStopped=false}ScanObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);try{if(this.hasAccumulation){this.accumulation=this.accumulator(this.accumulation,x)}else{this.accumulation=this.hasSeed?this.accumulator(this.seed,x):x;this.hasAccumulation=true}}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)};ScanObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e)}};ScanObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed);this.observer.onCompleted()}};ScanObserver.prototype.dispose=function(){this.isStopped=true};ScanObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};observableProto.scan=function(){var hasSeed=false,seed,accumulator,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new ScanObservable(this,accumulator,hasSeed,seed)};observableProto.skipLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&o.onNext(q.shift())},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}for(var args=[],i=start,len=arguments.length;icount&&q.shift()},function(e){o.onError(e)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()})},source)};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){o.onNext(q);o.onCompleted()})},source)};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new ArgumentOutOfRangeError}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};function concatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.concatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})})}return isFunction(selector)?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this,onNextFunc=bindCallback(onNext,thisArg,2),onErrorFunc=bindCallback(onError,thisArg,1),onCompletedFunc=bindCallback(onCompleted,thisArg,0);return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNextFunc(x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onErrorFunc(err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompletedFunc()}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},this).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;defaultValue===undefined&&(defaultValue=null);return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},function(e){observer.onError(e)},function(){!found&&observer.onNext(defaultValue);observer.onCompleted()})},source)};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i0){o.onNext(x);remaining<=0&&o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.takeWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running=callback(x,i++,source)}catch(e){o.onError(e);return}if(running){o.onNext(x)}else{o.onCompleted()}}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};var FilterObservable=function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source=source;this.predicate=bindCallback(predicate,thisArg,3);__super__.call(this)}FilterObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.predicate,this))};function innerPredicate(predicate,self){return function(x,i,o){return self.predicate(x,i,o)&&predicate.call(this,x,i,o)}}FilterObservable.prototype.internalFilter=function(predicate,thisArg){return new FilterObservable(this.source,innerPredicate(predicate,this),thisArg)};function InnerObserver(o,predicate,source){this.o=o;this.predicate=predicate;this.source=source;this.i=0;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var shouldYield=tryCatch(this.predicate)(x,this.i++,this.source);if(shouldYield===errorObj){return this.o.onError(shouldYield.e)}shouldYield&&this.o.onNext(x)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return FilterObservable}(ObservableBase);observableProto.filter=observableProto.where=function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg)};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(o){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){o.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){o.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},function(e){o.onError(e)},function(){o.onNext(list);o.onCompleted()})},source)}function firstOnly(x){if(x.length===0){throw new EmptyError}return x[0]}observableProto.aggregate=function(){var hasSeed=false,accumulator,seed,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new AnonymousObservable(function(o){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){return o.onError(e)}},function(e){o.onError(e)},function(){hasValue&&o.onNext(accumulation);!hasValue&&hasSeed&&o.onNext(seed);!hasValue&&!hasSeed&&o.onError(new EmptyError);o.onCompleted()})},source)};var ReduceObservable=function(__super__){inherits(ReduceObservable,__super__);function ReduceObservable(source,acc,hasSeed,seed){this.source=source;this.acc=acc;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ReduceObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new InnerObserver(observer,this))};function InnerObserver(o,parent){this.o=o;this.acc=parent.acc;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.result=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.result=tryCatch(this.acc)(this.result,x)}else{this.result=this.hasSeed?tryCatch(this.acc)(this.seed,x):x;this.hasAccumulation=true}if(this.result===errorObj){this.o.onError(this.result.e)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.hasValue&&this.o.onNext(this.result);!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);!this.hasValue&&!this.hasSeed&&this.o.onError(new EmptyError);this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return ReduceObservable}(ObservableBase);observableProto.reduce=function(accumulator){var hasSeed=false;if(arguments.length===2){hasSeed=true;var seed=arguments[1]}return new ReduceObservable(this,accumulator,hasSeed,seed)};observableProto.some=function(predicate,thisArg){var source=this;return predicate?source.filter(predicate,thisArg).some():new AnonymousObservable(function(observer){return source.subscribe(function(){observer.onNext(true);observer.onCompleted()},function(e){observer.onError(e)},function(){observer.onNext(false);observer.onCompleted()})},source)};observableProto.any=function(){return this.some.apply(this,arguments)};observableProto.isEmpty=function(){return this.any().map(not)};observableProto.every=function(predicate,thisArg){return this.filter(function(v){return!predicate(v)},thisArg).some().map(not)};observableProto.all=function(){return this.every.apply(this,arguments)};observableProto.includes=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(false);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){o.onNext(true);o.onCompleted()}},function(e){o.onError(e)},function(){o.onNext(false);o.onCompleted()})},this)};observableProto.contains=function(searchElement,fromIndex){observableProto.includes(searchElement,fromIndex)};observableProto.count=function(predicate,thisArg){return predicate?this.filter(predicate,thisArg).count():this.reduce(function(count){return count+1},0)};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(-1);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){o.onNext(i);o.onCompleted()}i++},function(e){o.onError(e)},function(){o.onNext(-1);o.onCompleted()})},source)};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.reduce(function(prev,curr){return prev+curr},0)};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.average=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).average():this.reduce(function(prev,cur){return{sum:prev.sum+cur,count:prev.count+1}},{sum:0,count:0}).map(function(s){if(s.count===0){throw new EmptyError}return s.sum/s.count})};observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){o.onError(e);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(doner){o.onNext(false);o.onCompleted()}else{ql.push(x)}},function(e){o.onError(e)},function(){donel=true;if(ql.length===0){if(qr.length>0){o.onNext(false);o.onCompleted()}else if(doner){o.onNext(true);o.onCompleted()}}});(isArrayLike(second)||isIterable(second))&&(second=observableFrom(second));isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){o.onError(exception);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(donel){o.onNext(false);o.onCompleted()}else{qr.push(x)}},function(e){o.onError(e)},function(){doner=true;if(qr.length===0){if(ql.length>0){o.onNext(false);o.onCompleted()}else if(donel){o.onNext(true);o.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)},first)};function elementAtOrDefault(source,index,hasDefault,defaultValue){if(index<0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(o){var i=index;return source.subscribe(function(x){if(i--===0){o.onNext(x);o.onCompleted()}},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new ArgumentOutOfRangeError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.elementAt=function(index){return elementAtOrDefault(this,index,false)};observableProto.elementAtOrDefault=function(index,defaultValue){return elementAtOrDefault(this,index,true,defaultValue)};function singleOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){if(seenValue){o.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.single=function(predicate,thisArg){return predicate&&isFunction(predicate)?this.where(predicate,thisArg).single():singleOrDefaultAsync(this,false)};observableProto.singleOrDefault=function(predicate,defaultValue,thisArg){return predicate&&isFunction(predicate)?this.filter(predicate,thisArg).singleOrDefault(null,defaultValue):singleOrDefaultAsync(this,true,defaultValue)};function firstOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){return source.subscribe(function(x){o.onNext(x);o.onCompleted()},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new EmptyError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.first=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).first():firstOrDefaultAsync(this,false)};observableProto.firstOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate).firstOrDefault(null,defaultValue):firstOrDefaultAsync(this,true,defaultValue)};function lastOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){value=x;seenValue=true},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.last=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).last():lastOrDefaultAsync(this,false)};observableProto.lastOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate,thisArg).lastOrDefault(null,defaultValue):lastOrDefaultAsync(this,true,defaultValue)};function findValue(source,predicate,thisArg,yieldIndex){var callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=callback(x,i,source)}catch(e){o.onError(e);return}if(shouldRun){o.onNext(yieldIndex?i:x);o.onCompleted()}else{i++}},function(e){o.onError(e)},function(){o.onNext(yieldIndex?-1:undefined);o.onCompleted()})},source)}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};observableProto.toSet=function(){if(typeof root.Set==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var s=new root.Set;return source.subscribe(function(x){s.add(x)},function(e){o.onError(e)},function(){o.onNext(s);o.onCompleted()})},source)};observableProto.toMap=function(keySelector,elementSelector){if(typeof root.Map==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){o.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){o.onError(e);return}}m.set(key,element)},function(e){o.onError(e)},function(){o.onNext(m);o.onCompleted()})},source)};var fnString="function",throwString="throw",isObject=Rx.internals.isObject;function toThunk(obj,ctx){if(Array.isArray(obj)){return objectToThunk.call(ctx,obj)}if(isGeneratorFunction(obj)){return observableSpawn(obj.call(ctx))}if(isGenerator(obj)){return observableSpawn(obj)}if(isObservable(obj)){return observableToThunk(obj)}if(isPromise(obj)){return promiseToThunk(obj)}if(typeof obj===fnString){return obj}if(isObject(obj)||Array.isArray(obj)){return objectToThunk.call(ctx,obj)}return obj}function objectToThunk(obj){var ctx=this;return function(done){var keys=Object.keys(obj),pending=keys.length,results=new obj.constructor,finished;if(!pending){timeoutScheduler.schedule(function(){done(null,results)});return}for(var i=0,len=keys.length;i2){for(var res=[],i=1,len=arguments.length;i0){o.onNext(q.shift())}}var subscription=combineLatestSource(this.source,this.pauser.distinctUntilChanged().startWith(false),function(data,shouldFire){return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){drainQueue()}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){o.onNext(results.data)}else{q.push(results.data)}}},function(err){drainQueue();o.onError(err)},function(){drainQueue();o.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};var ControlledObservable=function(__super__){inherits(ControlledObservable,__super__);function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue,scheduler){__super__.call(this,subscribe,source);this.subject=new ControlledSubject(enableQueue,scheduler);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){return this.subject.request(numberOfItems==null?-1:numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=function(__super__){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue,scheduler){enableQueue==null&&(enableQueue=true);__super__.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=disposableEmpty;this.error=null;this.hasFailed=false;this.hasCompleted=false;this.scheduler=scheduler||currentThreadScheduler}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0){this.subject.onCompleted()}else{this.queue.push(Notification.createOnCompleted())}},onError:function(error){this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0){this.subject.onError(error)}else{this.queue.push(Notification.createOnError(error))}},onNext:function(value){var hasRequested=false;if(this.requestedCount===0){this.enableQueue&&this.queue.push(Notification.createOnNext(value))}else{this.requestedCount!==-1&&this.requestedCount--===0&&this.disposeCurrentRequest();hasRequested=true}hasRequested&&this.subject.onNext(value)},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>=numberOfItems&&numberOfItems>0||this.queue.length>0&&this.queue[0].kind!=="N"){var first=this.queue.shift();first.accept(this.subject);if(first.kind==="N"){numberOfItems--}else{this.disposeCurrentRequest();this.queue=[]}}return{numberOfItems:numberOfItems,returnValue:this.queue.length!==0}}return{numberOfItems:numberOfItems,returnValue:false}},request:function(number){this.disposeCurrentRequest();var self=this;this.requestedDisposable=this.scheduler.scheduleWithState(number,function(s,i){var r=self._processRequest(i),remaining=r.numberOfItems;if(!r.returnValue){self.requestedCount=remaining;self.requestedDisposable=disposableCreate(function(){self.requestedCount=0})}});return this.requestedDisposable},disposeCurrentRequest:function(){this.requestedDisposable.dispose();this.requestedDisposable=disposableEmpty}});return ControlledSubject}(Observable);observableProto.controlled=function(enableQueue,scheduler){if(enableQueue&&isScheduler(enableQueue)){scheduler=enableQueue;enableQueue=true}if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue,scheduler); -};var StopAndWaitObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new StopAndWaitObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(1)});return this.subscription}inherits(StopAndWaitObservable,__super__);function StopAndWaitObservable(source){__super__.call(this,subscribe,source);this.source=source}var StopAndWaitObserver=function(__sub__){inherits(StopAndWaitObserver,__sub__);function StopAndWaitObserver(observer,observable,cancel){__sub__.call(this);this.observer=observer;this.observable=observable;this.cancel=cancel}var stopAndWaitObserverProto=StopAndWaitObserver.prototype;stopAndWaitObserverProto.completed=function(){this.observer.onCompleted();this.dispose()};stopAndWaitObserverProto.error=function(error){this.observer.onError(error);this.dispose()};stopAndWaitObserverProto.next=function(value){this.observer.onNext(value);var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(1)})};stopAndWaitObserverProto.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return StopAndWaitObserver}(AbstractObserver);return StopAndWaitObservable}(Observable);ControlledObservable.prototype.stopAndWait=function(){return new StopAndWaitObservable(this)};var WindowedObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new WindowedObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(self.windowSize)});return this.subscription}inherits(WindowedObservable,__super__);function WindowedObservable(source,windowSize){__super__.call(this,subscribe,source);this.source=source;this.windowSize=windowSize}var WindowedObserver=function(__sub__){inherits(WindowedObserver,__sub__);function WindowedObserver(observer,observable,cancel){this.observer=observer;this.observable=observable;this.cancel=cancel;this.received=0}var windowedObserverPrototype=WindowedObserver.prototype;windowedObserverPrototype.completed=function(){this.observer.onCompleted();this.dispose()};windowedObserverPrototype.error=function(error){this.observer.onError(error);this.dispose()};windowedObserverPrototype.next=function(value){this.observer.onNext(value);this.received=++this.received%this.observable.windowSize;if(this.received===0){var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(self.observable.windowSize)})}};windowedObserverPrototype.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return WindowedObserver}(AbstractObserver);return WindowedObservable}(Observable);ControlledObservable.prototype.windowed=function(windowSize){return new WindowedObservable(this,windowSize)};observableProto.pipe=function(dest){var source=this.pausableBuffered();function onDrain(){source.resume()}dest.addListener("drain",onDrain);source.subscribe(function(x){!dest.write(String(x))&&source.pause()},function(err){dest.emit("error",err)},function(){!dest._isStdio&&dest.end();dest.removeListener("drain",onDrain)});source.resume();return dest};observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())},source):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,windowSize,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler))};observableProto.shareReplay=function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.hasError=false}addProperties(BehaviorSubject.prototype,Observer,{getValue:function(){checkDisposed(this);if(this.hasError){throw this.error}return this.value},hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i=min){return num}}candidate=min|1;while(candidate>>16;key=key+(key<<3);key=key^key>>>4;key=key*c2;key=key^key>>>15;return key}var getHashCode=function(){var uniqueIdCounter=0;return function(obj){if(obj==null){throw new Error(noSuchkey)}if(typeof obj==="string"){return stringHashFn(obj)}if(typeof obj==="number"){return numberHashFn(obj)}if(typeof obj==="boolean"){return obj===true?1:0}if(obj instanceof Date){return numberHashFn(obj.valueOf())}if(obj instanceof RegExp){return stringHashFn(obj.toString())}if(typeof obj.valueOf==="function"){var valueOf=obj.valueOf();if(typeof valueOf==="number"){return numberHashFn(valueOf)}if(typeof valueOf==="string"){return stringHashFn(valueOf)}}if(obj.hashCode){return obj.hashCode()}var id=17*uniqueIdCounter++;obj.hashCode=function(){return id};return id}}();function newEntry(){return{key:null,value:null,next:0,hashCode:0}}function Dictionary(capacity,comparer){if(capacity<0){throw new ArgumentOutOfRangeError}if(capacity>0){this._initialize(capacity)}this.comparer=comparer||defaultComparer;this.freeCount=0;this.size=0;this.freeList=-1}var dictionaryProto=Dictionary.prototype;dictionaryProto._initialize=function(capacity){var prime=getPrime(capacity),i;this.buckets=new Array(prime);this.entries=new Array(prime);for(i=0;i=0;index2=this.entries[index2].next){if(this.entries[index2].hashCode===num&&this.comparer(this.entries[index2].key,key)){if(add){throw new Error(duplicatekey)}this.entries[index2].value=value;return}}if(this.freeCount>0){index3=this.freeList;this.freeList=this.entries[index3].next;--this.freeCount}else{if(this.size===this.entries.length){this._resize();index1=num%this.buckets.length}index3=this.size;++this.size}this.entries[index3].hashCode=num;this.entries[index3].next=this.buckets[index1];this.entries[index3].key=key;this.entries[index3].value=value;this.buckets[index1]=index3};dictionaryProto._resize=function(){var prime=getPrime(this.size*2),numArray=new Array(prime);for(index=0;index=0;index3=this.entries[index3].next){if(this.entries[index3].hashCode===num&&this.comparer(this.entries[index3].key,key)){if(index2<0){this.buckets[index1]=this.entries[index3].next}else{this.entries[index2].next=this.entries[index3].next}this.entries[index3].hashCode=-1;this.entries[index3].next=this.freeList;this.entries[index3].key=null;this.entries[index3].value=null;this.freeList=index3;++this.freeCount;return true}else{index2=index3}}}return false};dictionaryProto.clear=function(){var index,len;if(this.size<=0){return}for(index=0,len=this.buckets.length;index=0;index=this.entries[index].next){if(this.entries[index].hashCode===num&&this.comparer(this.entries[index].key,key)){return index}}}return-1};dictionaryProto.count=function(){return this.size-this.freeCount};dictionaryProto.tryGetValue=function(key){var entry=this._findEntry(key);return entry>=0?this.entries[entry].value:undefined};dictionaryProto.getValues=function(){var index=0,results=[];if(this.entries){for(var index1=0;index1=0){results[index++]=this.entries[index1].value}}}return results};dictionaryProto.get=function(key){var entry=this._findEntry(key);if(entry>=0){return this.entries[entry].value}throw new Error(noSuchkey)};dictionaryProto.set=function(key,value){this._insert(key,value,false)};dictionaryProto.containskey=function(key){return this._findEntry(key)>=0};return Dictionary}();observableProto.join=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var leftDone=false,rightDone=false;var leftId=0,rightId=0;var leftMap=new Dictionary,rightMap=new Dictionary;group.add(left.subscribe(function(value){var id=leftId++;var md=new SingleAssignmentDisposable;leftMap.add(id,value);group.add(md);var expire=function(){leftMap.remove(id)&&leftMap.count()===0&&leftDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));rightMap.getValues().forEach(function(v){var result;try{result=resultSelector(value,v)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){leftDone=true;(rightDone||leftMap.count()===0)&&observer.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++;var md=new SingleAssignmentDisposable;rightMap.add(id,value);group.add(md);var expire=function(){rightMap.remove(id)&&rightMap.count()===0&&rightDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));leftMap.getValues().forEach(function(v){var result;try{result=resultSelector(v,value)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){rightDone=true;(leftDone||rightMap.count()===0)&&observer.onCompleted()}));return group},left)};observableProto.groupJoin=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var r=new RefCountDisposable(group);var leftMap=new Dictionary,rightMap=new Dictionary;var leftId=0,rightId=0;function handleError(e){return function(v){v.onError(e)}}group.add(left.subscribe(function(value){var s=new Subject;var id=leftId++;leftMap.add(id,s);var result;try{result=resultSelector(value,addRef(s,r))}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(result);rightMap.getValues().forEach(function(v){s.onNext(v)});var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){leftMap.remove(id)&&s.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire))},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},observer.onCompleted.bind(observer)));group.add(right.subscribe(function(value){var id=rightId++;rightMap.add(id,value);var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){rightMap.remove(id);group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire));leftMap.getValues().forEach(function(v){v.onNext(value)})},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)}));return r},left)};observableProto.buffer=function(bufferOpeningsOrClosingSelector,bufferClosingSelector){return this.window.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.window=function(windowOpeningsOrClosingSelector,windowClosingSelector){if(arguments.length===1&&typeof arguments[0]!=="function"){return observableWindowWithBoundaries.call(this,windowOpeningsOrClosingSelector)}return typeof windowOpeningsOrClosingSelector==="function"?observableWindowWithClosingSelector.call(this,windowOpeningsOrClosingSelector):observableWindowWithOpenings.call(this,windowOpeningsOrClosingSelector,windowClosingSelector)};function observableWindowWithOpenings(windowOpenings,windowClosingSelector){return windowOpenings.groupJoin(this,windowClosingSelector,observableEmpty,function(_,win){return win})}function observableWindowWithBoundaries(windowBoundaries){var source=this;return new AnonymousObservable(function(observer){var win=new Subject,d=new CompositeDisposable,r=new RefCountDisposable(d);observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));isPromise(windowBoundaries)&&(windowBoundaries=observableFromPromise(windowBoundaries));d.add(windowBoundaries.subscribe(function(w){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r))},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));return r},source)}function observableWindowWithClosingSelector(windowClosingSelector){var source=this;return new AnonymousObservable(function(observer){var m=new SerialDisposable,d=new CompositeDisposable(m),r=new RefCountDisposable(d),win=new Subject;observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));function createWindowClose(){var windowClose;try{windowClose=windowClosingSelector()}catch(e){observer.onError(e);return}isPromise(windowClose)&&(windowClose=observableFromPromise(windowClose));var m1=new SingleAssignmentDisposable;m.setDisposable(m1);m1.setDisposable(windowClose.take(1).subscribe(noop,function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r));createWindowClose()}))}createWindowClose();return r},source)}observableProto.pairwise=function(){var source=this;return new AnonymousObservable(function(observer){var previous,hasPrevious=false;return source.subscribe(function(x){if(hasPrevious){observer.onNext([previous,x])}else{hasPrevious=true}previous=x},observer.onError.bind(observer),observer.onCompleted.bind(observer))},source)};observableProto.partition=function(predicate,thisArg){return[this.filter(predicate,thisArg),this.filter(function(x,i,o){return!predicate.call(thisArg,x,i,o)})]};var WhileEnumerable=function(__super__){inherits(WhileEnumerable,__super__);function WhileEnumerable(c,s){this.c=c;this.s=s}WhileEnumerable.prototype[$iterator$]=function(){var self=this;return{next:function(){return self.c()?{done:false,value:self.s}:{done:true,value:void 0}}}};return WhileEnumerable}(Enumerable);function enumerableWhile(condition,source){return new WhileEnumerable(condition,source)}observableProto.letBind=observableProto["let"]=function(func){return func(this)};Observable["if"]=Observable.ifThen=function(condition,thenSource,elseSourceOrScheduler){return observableDefer(function(){elseSourceOrScheduler||(elseSourceOrScheduler=observableEmpty());isPromise(thenSource)&&(thenSource=observableFromPromise(thenSource));isPromise(elseSourceOrScheduler)&&(elseSourceOrScheduler=observableFromPromise(elseSourceOrScheduler));typeof elseSourceOrScheduler.now==="function"&&(elseSourceOrScheduler=observableEmpty(elseSourceOrScheduler));return condition()?thenSource:elseSourceOrScheduler})};Observable["for"]=Observable.forIn=function(sources,resultSelector,thisArg){return enumerableOf(sources,resultSelector,thisArg).concat()};var observableWhileDo=Observable["while"]=Observable.whileDo=function(condition,source){isPromise(source)&&(source=observableFromPromise(source));return enumerableWhile(condition,source).concat()};observableProto.doWhile=function(condition){return observableConcat([this,observableWhileDo(condition,this)])};Observable["case"]=Observable.switchCase=function(selector,sources,defaultSourceOrScheduler){return observableDefer(function(){isPromise(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableFromPromise(defaultSourceOrScheduler));defaultSourceOrScheduler||(defaultSourceOrScheduler=observableEmpty());typeof defaultSourceOrScheduler.now==="function"&&(defaultSourceOrScheduler=observableEmpty(defaultSourceOrScheduler));var result=sources[selector()];isPromise(result)&&(result=observableFromPromise(result));return result||defaultSourceOrScheduler})};observableProto.expand=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[],m=new SerialDisposable,d=new CompositeDisposable(m),activeCount=0,isAcquired=false;var ensureActive=function(){var isOwner=false;if(q.length>0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d},this)};Observable.forkJoin=function(){var allSources=[];if(Array.isArray(arguments[0])){allSources=arguments[0]}else{for(var i=0,len=arguments.length;i0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count);self(count+1,d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!==undefined&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){period=periodOrScheduler;return observableTimerDateAndPeriod(dueTime.getTime(),period,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)},source)}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.debounce=observableProto.throttleWithTimeout=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)},this)};observableProto.throttle=function(dueTime,scheduler){return this.debounce(dueTime,scheduler)};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}o.onCompleted()})},source)};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){o.onNext(next.value)}}o.onCompleted()})},source)};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();now-next.interval<=duration&&res.push(next.value)}o.onNext(res);o.onCompleted()})},source)};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))},source)};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()}))},source)};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler[schedulerMethod](endTime,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.throttleFirst=function(windowDuration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var duration=+windowDuration||0;if(duration<=0){throw new RangeError("windowDuration cannot be less or equal zero.")}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext===0||now-lastOnNext>=duration){lastOnNext=now;o.onNext(x)}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.transduce=function(transducer){var source=this;function transformForObserver(o){return{"@@transducer/init":function(){return o},"@@transducer/step":function(obs,input){return obs.onNext(input)},"@@transducer/result":function(obs){return obs.onCompleted()}}}return new AnonymousObservable(function(o){var xform=transducer(transformForObserver(o));return source.subscribe(function(v){try{xform["@@transducer/step"](o,v)}catch(e){o.onError(e)}},function(e){o.onError(e)},function(){xform["@@transducer/result"](o)})},source)};observableProto.exclusive=function(){var sources=this;return new AnonymousObservable(function(observer){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},observer.onError.bind(observer),function(){isStopped=true;if(!hasCurrent&&g.length===1){observer.onCompleted()}}));return g},this)};observableProto.exclusiveMap=function(selector,thisArg){var sources=this,selectorFunc=bindCallback(selector,thisArg,3);return new AnonymousObservable(function(observer){var index=0,hasCurrent=false,isStopped=true,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){var result;try{result=selectorFunc(x,index++,innerSource)}catch(e){observer.onError(e);return}observer.onNext(result)},function(e){observer.onError(e)},function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},function(e){observer.onError(e)},function(){isStopped=true;if(g.length===1&&!hasCurrent){observer.onCompleted()}}));return g},this)};Rx.VirtualTimeScheduler=function(__super__){function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new ArgumentOutOfRangeError}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],subscribe=state[1];var sub=tryCatch(subscribe)(ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function AnonymousObservable(subscribe,parent){this.source=parent;function s(observer){var ado=new AutoDetachObserver(observer),state=[ado,subscribe];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}__super__.call(this,s)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result===errorObj){this.dispose();thrower(result.e)}};AutoDetachObserverPrototype.error=function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.completed=function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(){return this.m.getDisposable()};AutoDetachObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,__super__);function Subject(){__super__.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[];this.hasError=false}addProperties(Subject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(!this.isStopped){this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},onCompleted:function(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped=true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i=0;i1){for(var i=1;i=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){storage.removeItem("debug")}else{storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=storage.debug}catch(e){}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}},{"./debug":6}],6:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(msy?1:x=rStartingLine&&lineNumber<=rEndingLine}function isNodeFrame(stackLine){return stackLine.indexOf("(module.js:")!==-1||stackLine.indexOf("(node.js:")!==-1}function captureLine(){if(!hasStacks){return}try{throw new Error}catch(e){var lines=e.stack.split("\n");var firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2];var fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber){return}rFileName=fileNameAndLineNumber[0];return fileNameAndLineNumber[1]}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1){return[attempt1[1],Number(attempt1[2])]}var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2){return[attempt2[1],Number(attempt2[2])]}var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3){return[attempt3[1],Number(attempt3[2])]}}var EmptyError=Rx.EmptyError=function(){this.message="Sequence contains no elements.";this.name="EmptyError";Error.call(this)};EmptyError.prototype=Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError=function(){this.message="Object has been disposed";this.name="ObjectDisposedError";Error.call(this)};ObjectDisposedError.prototype=Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError=function(){this.message="Argument out of range";this.name="ArgumentOutOfRangeError";Error.call(this)};ArgumentOutOfRangeError.prototype=Error.prototype;var NotSupportedError=Rx.NotSupportedError=function(message){this.message=message||"This operation is not supported";this.name="NotSupportedError";Error.call(this)};NotSupportedError.prototype=Error.prototype;var NotImplementedError=Rx.NotImplementedError=function(message){this.message=message||"This operation is not implemented";this.name="NotImplementedError";Error.call(this)};NotImplementedError.prototype=Error.prototype;var notImplemented=Rx.helpers.notImplemented=function(){throw new NotImplementedError};var notSupported=Rx.helpers.notSupported=function(){throw new NotSupportedError};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};var isIterable=Rx.helpers.isIterable=function(o){return o[$iterator$]!==undefined};var isArrayLike=Rx.helpers.isArrayLike=function(o){return o&&o.length!==undefined};Rx.helpers.iterator=$iterator$;var bindCallback=Rx.internals.bindCallback=function(func,thisArg,argCount){if(typeof thisArg==="undefined"){return func}switch(argCount){case 0:return function(){return func.call(thisArg)};case 1:return function(arg){return func.call(thisArg,arg)};case 2:return function(value,index){return func.call(thisArg,value,index)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)}}return function(){return func.apply(thisArg,arguments)}};var dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,supportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,stringProto=String.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{supportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){supportNodeClass=true}var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);var isObject=Rx.internals.isObject=function(value){var type=typeof value;return value&&(type=="function"||type=="object")||false};function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=dontEnumsLength;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index-1}})}}stackA.pop();stackB.pop();return result}var hasProp={}.hasOwnProperty,slice=Array.prototype.slice;var inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){for(var sources=[],i=1,len=arguments.length;i=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left0){var item=queue.shift();!item.isCancelled()&&item.invoke()}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue=[si];var result=tryCatch(runTrampoline)();queue=null;if(result===errorObj){return thrower(result.e)}}else{queue.push(si)}return si.disposable}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired=function(){return!queue};return currentScheduler}();var scheduleMethod,clearMethod;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else if(!!root.WScript){localSetTimeout=function(fn,time){root.WScript.Sleep(time);fn()}}else{throw new NotSupportedError}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;clearMethod=function(handle){delete tasksByHandle[handle]};function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle)},0)}else{var task=tasksByHandle[handle];if(task){currentlyRunning=true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning=false;if(result===errorObj){return thrower(result.e)}}}}var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(isFunction(setImmediate)){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;setImmediate(function(){runTask(id)});return id}}else if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;process.nextTick(function(){runTask(id)});return id}}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random();function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length))}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else if(root.attachEvent){root.attachEvent("onmessage",onGlobalPostMessage)}else{root.onmessage=onGlobalPostMessage}scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;root.postMessage(MSG_PREFIX+currentId,"*");return id}}else if(!!root.MessageChannel){var channel=new root.MessageChannel;channel.port1.onmessage=function(e){runTask(e.data)};scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;channel.port2.postMessage(id);return id}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");var id=nextHandle++;tasksByHandle[id]=action;scriptElement.onreadystatechange=function(){runTask(id);scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement);return id}}else{scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;localSetTimeout(function(){runTask(id)},0);return id}}})();var timeoutScheduler=Scheduler.timeout=Scheduler["default"]=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime),disposable=new SingleAssignmentDisposable;if(dt===0){return scheduler.scheduleWithState(state,action)}var id=localSetTimeout(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(__super__){function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,__super__);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler;this._recursiveOriginal=null;this._recursiveWrapper=null;__super__.call(this,this._scheduler.now.bind(this._scheduler),scheduleNow,scheduleRelative,scheduleAbsolute); +}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind=kind;this.value=value;this.exception=exception;this._accept=accept;this._acceptObservable=acceptObservable;this.toString=toString}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var self=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){return new Notification("N",value,null,_accept,_acceptObservable,toString)}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(e){return new Notification("E",null,e,_accept,_acceptObservable,toString)}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){return new Notification("C",null,null,_accept,_acceptObservable,toString)}}();var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){var self=this;return new AnonymousObserver(function(x){self.onNext(x)},function(err){self.onError(err)},function(){self.onCompleted()})};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){var cb=bindCallback(handler,thisArg,1);return new AnonymousObserver(function(x){return cb(notificationCreateOnNext(x))},function(e){return cb(notificationCreateOnError(e))},function(){return cb(notificationCreateOnCompleted())})};Observer.prototype.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};Observer.prototype.makeSafe=function(disposable){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,disposable)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false}AbstractObserver.prototype.next=notImplemented;AbstractObserver.prototype.error=notImplemented;AbstractObserver.prototype.completed=notImplemented;AbstractObserver.prototype.onNext=function(value){!this.isStopped&&this.next(value)};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(__super__){inherits(CheckedObserver,__super__);function CheckedObserver(observer){__super__.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();var res=tryCatch(this._observer.onNext).call(this._observer,value);this._state=0;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onError=function(err){this.checkAccess();var res=tryCatch(this._observer.onError).call(this._observer,err);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();var res=tryCatch(this._observer.onCompleted).call(this._observer);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(e){var self=this;this.queue.push(function(){self.observer.onError(e)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this,function(parent,self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}var res=tryCatch(work)();if(res===errorObj){parent.queue=[];parent.hasFaulted=true;return thrower(res.e)}self(parent)}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(scheduler,observer,cancel){__super__.call(this,scheduler,observer);this._cancel=cancel}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};ObserveOnObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this._cancel&&this._cancel.dispose();this._cancel=null};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function makeSubscribe(self,subscribe){return function(o){var oldOnError=o.onError;o.onError=function(e){makeStackTraceLong(e,self);oldOnError.call(o,e)};return subscribe.call(self,o)}}function Observable(subscribe){if(Rx.config.longStackSupport&&hasStacks){var e=tryCatch(thrower)(new Error).e;this.stack=e.stack.substring(e.stack.indexOf("\n")+1);this._subscribe=makeSubscribe(this,subscribe)}else{this._subscribe=subscribe}}observableProto=Observable.prototype;Observable.isObservable=function(o){return o&&isFunction(o.subscribe)};observableProto.subscribe=observableProto.forEach=function(oOrOnNext,onError,onCompleted){return this._subscribe(typeof oOrOnNext==="object"?oOrOnNext:observerCreate(oOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();var ObservableBase=Rx.ObservableBase=function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function ObservableBase(){__super__.call(this,subscribe)}ObservableBase.prototype.subscribeCore=notImplemented;return ObservableBase}(Observable);var FlatMapObservable=function(__super__){inherits(FlatMapObservable,__super__);function FlatMapObservable(source,selector,resultSelector,thisArg){this.resultSelector=Rx.helpers.isFunction(resultSelector)?resultSelector:null;this.selector=Rx.internals.bindCallback(Rx.helpers.isFunction(selector)?selector:function(){return selector},thisArg,3);this.source=source;__super__.call(this)}FlatMapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.selector,this.resultSelector,this))};function InnerObserver(observer,selector,resultSelector,source){this.i=0;this.selector=selector;this.resultSelector=resultSelector;this.source=source;this.isStopped=false;this.o=observer}InnerObserver.prototype._wrapResult=function(result,x,i){return this.resultSelector?result.map(function(y,i2){return this.resultSelector(x,y,i,i2)},this):result};InnerObserver.prototype.onNext=function(x){if(this.isStopped)return;var i=this.i++;var result=tryCatch(this.selector)(x,i,this.source);if(result===errorObj){return this.o.onError(result.e)}Rx.helpers.isPromise(result)&&(result=Rx.Observable.fromPromise(result));(Rx.helpers.isArrayLike(result)||Rx.helpers.isIterable(result))&&(result=Rx.Observable.from(result));this.o.onNext(this._wrapResult(result,x,i))};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};return FlatMapObservable}(ObservableBase);var Enumerable=Rx.internals.Enumerable=function(){};var ConcatEnumerableObservable=function(__super__){inherits(ConcatEnumerableObservable,__super__);function ConcatEnumerableObservable(sources){this.sources=sources;__super__.call(this)}ConcatEnumerableObservable.prototype.subscribeCore=function(o){var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](),function(e,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(new InnerObserver(o,self,e)))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};function InnerObserver(o,s,e){this.o=o;this.s=s;this.e=e;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.o.onNext(x)}};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.s(this.e)}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err);return true}return false};return ConcatEnumerableObservable}(ObservableBase);Enumerable.prototype.concat=function(){return new ConcatEnumerableObservable(this)};var CatchErrorObservable=function(__super__){inherits(CatchErrorObservable,__super__);function CatchErrorObservable(sources){this.sources=sources;__super__.call(this)}CatchErrorObservable.prototype.subscribeCore=function(o){var e=this.sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return lastException!==null?o.onError(lastException):o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},self,function(){o.onCompleted()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};return CatchErrorObservable}(ObservableBase);Enumerable.prototype.catchError=function(){return new CatchErrorObservable(this)};Enumerable.prototype.catchErrorWhen=function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject,notifier=new Subject,handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){if(lastException){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable;var inner=new SingleAssignmentDisposable;subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex)},function(){o.onCompleted()}));exceptions.onNext(exn)},function(){o.onCompleted()}))});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var RepeatEnumerable=function(__super__){inherits(RepeatEnumerable,__super__);function RepeatEnumerable(v,c){this.v=v;this.c=c==null?-1:c}RepeatEnumerable.prototype[$iterator$]=function(){return new RepeatEnumerator(this)};function RepeatEnumerator(p){this.v=p.v;this.l=p.c}RepeatEnumerator.prototype.next=function(){if(this.l===0){return doneEnumerator}if(this.l>0){this.l--}return{done:false,value:this.v}};return RepeatEnumerable}(Enumerable);var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){return new RepeatEnumerable(value,repeatCount)};var OfEnumerable=function(__super__){inherits(OfEnumerable,__super__);function OfEnumerable(s,fn,thisArg){this.s=s;this.fn=fn?bindCallback(fn,thisArg,3):null}OfEnumerable.prototype[$iterator$]=function(){return new OfEnumerator(this)};function OfEnumerator(p){this.i=-1;this.s=p.s;this.l=this.s.length;this.fn=p.fn}OfEnumerator.prototype.next=function(){return++this.imaxSafeInteger){return maxSafeInteger}return len}var observableFrom=Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isFunction(mapFn)){throw new Error("mapFn when provided must be a function")}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2)}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler)};var FromArrayObservable=function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args=args;this.scheduler=scheduler;__super__.call(this)}FromArrayObservable.prototype.subscribeCore=function(observer){var sink=new FromArraySink(observer,this);return sink.run()};return FromArrayObservable}(ObservableBase);function FromArraySink(observer,parent){this.observer=observer;this.parent=parent}FromArraySink.prototype.run=function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i0){observer.onNext(value);i>0&&i--}if(i===0){return observer.onCompleted()}recurse(i)}return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,loopRecursive)};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RepeatObservable(value,repeatCount,scheduler)};var JustObservable=function(__super__){inherits(JustObservable,__super__);function JustObservable(value,scheduler){this.value=value;this.scheduler=scheduler;__super__.call(this)}JustObservable.prototype.subscribeCore=function(observer){var sink=new JustSink(observer,this.value,this.scheduler);return sink.run()};function JustSink(observer,value,scheduler){this.observer=observer;this.value=value;this.scheduler=scheduler}function scheduleItem(s,state){var value=state[0],observer=state[1];observer.onNext(value);observer.onCompleted();return disposableEmpty}JustSink.prototype.run=function(){var state=[this.value,this.observer];return this.scheduler===immediateScheduler?scheduleItem(null,state):this.scheduler.scheduleWithState(state,scheduleItem)};return JustObservable}(ObservableBase);var observableReturn=Observable["return"]=Observable.just=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new JustObservable(value,scheduler)};var ThrowObservable=function(__super__){inherits(ThrowObservable,__super__);function ThrowObservable(error,scheduler){this.error=error;this.scheduler=scheduler;__super__.call(this)}ThrowObservable.prototype.subscribeCore=function(o){var sink=new ThrowSink(o,this);return sink.run()};function ThrowSink(o,p){this.o=o;this.p=p}function scheduleItem(s,state){var e=state[0],o=state[1];o.onError(e)}ThrowSink.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],scheduleItem)};return ThrowObservable}(ObservableBase);var observableThrow=Observable["throw"]=function(error,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new ThrowObservable(error,scheduler)};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(o){var disposable=disposableEmpty;var resource=tryCatch(resourceFactory)();if(resource===errorObj){return new CompositeDisposable(observableThrow(resource.e).subscribe(o),disposable)}resource&&(disposable=resource); +var source=tryCatch(observableFactory)(resource);if(source===errorObj){return new CompositeDisposable(observableThrow(source.e).subscribe(o),disposable)}return new CompositeDisposable(source.subscribe(o),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}var leftSubscribe=observerCreate(function(left){choiceL();choice===leftChoice&&observer.onNext(left)},function(e){choiceL();choice===leftChoice&&observer.onError(e)},function(){choiceL();choice===leftChoice&&observer.onCompleted()});var rightSubscribe=observerCreate(function(right){choiceR();choice===rightChoice&&observer.onNext(right)},function(e){choiceR();choice===rightChoice&&observer.onError(e)},function(){choiceR();choice===rightChoice&&observer.onCompleted()});leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));return new CompositeDisposable(leftSubscription,rightSubscription)})};function amb(p,c){return p.amb(c)}Observable.amb=function(){var acc=observableNever(),items;if(Array.isArray(arguments[0])){items=arguments[0]}else{var len=arguments.length;items=new Array(items);for(var i=0;i0){parent.handleSubscribe(parent.q.shift())}else{parent.activeCount--;parent.done&&parent.activeCount===0&&parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeObserver}();observableProto.merge=function(maxConcurrentOrOther){return typeof maxConcurrentOrOther!=="number"?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther)};var observableMerge=Observable.merge=function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler=immediateScheduler;for(i=1;i0})){var queuedValues=queues.map(function(x){return x.shift()}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},parent)};Observable.zip=function(){var len=arguments.length,args=new Array(len);for(var i=0;i0})){var res=queues.map(function(x){return x.shift()});o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){return o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}))})(idx)}return new CompositeDisposable(subscriptions)})};function asObservable(source){return function subscribe(o){return source.subscribe(o)}}observableProto.asObservable=function(){return new AnonymousObservable(asObservable(this),this)};function toArray(x){return x.toArray()}function notEmpty(x){return x.length>0}observableProto.bufferWithCount=function(count,skip){typeof skip!=="number"&&(skip=count);return this.windowWithCount(count,skip).flatMap(toArray).filter(notEmpty)};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};var DistinctUntilChangedObservable=function(__super__){inherits(DistinctUntilChangedObservable,__super__);function DistinctUntilChangedObservable(source,keyFn,comparer){this.source=source;this.keyFn=keyFn;this.comparer=comparer;__super__.call(this)}DistinctUntilChangedObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new DistinctUntilChangedObserver(o,this.keyFn,this.comparer))};return DistinctUntilChangedObservable}(ObservableBase);function DistinctUntilChangedObserver(o,keyFn,comparer){this.o=o;this.keyFn=keyFn;this.comparer=comparer;this.hasCurrentKey=false;this.currentKey=null;this.isStopped=false}DistinctUntilChangedObserver.prototype.onNext=function(x){if(this.isStopped){return}var key=x;if(isFunction(this.keyFn)){key=tryCatch(this.keyFn)(x);if(key===errorObj){return this.o.onError(key.e)}}if(this.hasCurrentKey){comparerEquals=tryCatch(this.comparer)(this.currentKey,key);if(comparerEquals===errorObj){return this.o.onError(comparerEquals.e)}}if(!this.hasCurrentKey||!comparerEquals){this.hasCurrentKey=true;this.currentKey=key;this.o.onNext(x)}};DistinctUntilChangedObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};DistinctUntilChangedObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};DistinctUntilChangedObserver.prototype.dispose=function(){this.isStopped=true};DistinctUntilChangedObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};observableProto.distinctUntilChanged=function(keyFn,comparer){comparer||(comparer=defaultComparer);return new DistinctUntilChangedObservable(this,keyFn,comparer)};var TapObservable=function(__super__){inherits(TapObservable,__super__);function TapObservable(source,observerOrOnNext,onError,onCompleted){this.source=source;this._oN=observerOrOnNext;this._oE=onError;this._oC=onCompleted;__super__.call(this)}TapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this))};function InnerObserver(o,p){this.o=o;this.t=!p._oN||isFunction(p._oN)?observerCreate(p._oN||noop,p._oE||noop,p._oC||noop):p._oN;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var res=tryCatch(this.t.onNext).call(this.t,x);if(res===errorObj){this.o.onError(res.e)}this.o.onNext(x)};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onError).call(this.t,err);if(res===errorObj){return this.o.onError(res.e)}this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onCompleted).call(this.t);if(res===errorObj){return this.o.onError(res.e)}this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return TapObservable}(ObservableBase);observableProto["do"]=observableProto.tap=observableProto.doAction=function(observerOrOnNext,onError,onCompleted){return new TapObservable(this,observerOrOnNext,onError,onCompleted)};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription=tryCatch(source.subscribe).call(source,observer);if(subscription===errorObj){action();return thrower(subscription.e)}return disposableCreate(function(){var r=tryCatch(subscription.dispose).call(subscription);action();r===errorObj&&thrower(r.e)})},this)};var IgnoreElementsObservable=function(__super__){inherits(IgnoreElementsObservable,__super__);function IgnoreElementsObservable(source){this.source=source;__super__.call(this)}IgnoreElementsObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o))};function InnerObserver(o){this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=noop;InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};return IgnoreElementsObservable}(ObservableBase);observableProto.ignoreElements=function(){return new IgnoreElementsObservable(this)};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})},source)};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchError()};observableProto.retryWhen=function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier)};var ScanObservable=function(__super__){inherits(ScanObservable,__super__);function ScanObservable(source,accumulator,hasSeed,seed){this.source=source;this.accumulator=accumulator;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ScanObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this))};return ScanObservable}(ObservableBase);function InnerObserver(o,parent){this.o=o;this.accumulator=parent.accumulator;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.accumulation=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype={onNext:function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.accumulation=tryCatch(this.accumulator)(this.accumulation,x)}else{this.accumulation=this.hasSeed?tryCatch(this.accumulator)(this.seed,x):x;this.hasAccumulation=true}if(this.accumulation===errorObj){return this.o.onError(this.accumulation.e)}this.o.onNext(this.accumulation)},onError:function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}},onCompleted:function(){if(!this.isStopped){this.isStopped=true;!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);this.o.onCompleted()}},dispose:function(){this.isStopped=true},fail:function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false}};observableProto.scan=function(){var hasSeed=false,seed,accumulator=arguments[0];if(arguments.length===2){hasSeed=true;seed=arguments[1]}return new ScanObservable(this,accumulator,hasSeed,seed)};observableProto.skipLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&o.onNext(q.shift())},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}for(var args=[],i=start,len=arguments.length;icount&&q.shift()},function(e){o.onError(e)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()})},source)};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){o.onNext(q);o.onCompleted()})},source)};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new ArgumentOutOfRangeError}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};function concatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.concatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})})}return isFunction(selector)?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this,onNextFunc=bindCallback(onNext,thisArg,2),onErrorFunc=bindCallback(onError,thisArg,1),onCompletedFunc=bindCallback(onCompleted,thisArg,0); +return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNextFunc(x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onErrorFunc(err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompletedFunc()}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},this).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;defaultValue===undefined&&(defaultValue=null);return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},function(e){observer.onError(e)},function(){!found&&observer.onNext(defaultValue);observer.onCompleted()})},source)};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i0){o.onNext(x);remaining<=0&&o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.takeWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running=callback(x,i++,source)}catch(e){o.onError(e);return}if(running){o.onNext(x)}else{o.onCompleted()}}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};var FilterObservable=function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source=source;this.predicate=bindCallback(predicate,thisArg,3);__super__.call(this)}FilterObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.predicate,this))};function innerPredicate(predicate,self){return function(x,i,o){return self.predicate(x,i,o)&&predicate.call(this,x,i,o)}}FilterObservable.prototype.internalFilter=function(predicate,thisArg){return new FilterObservable(this.source,innerPredicate(predicate,this),thisArg)};function InnerObserver(o,predicate,source){this.o=o;this.predicate=predicate;this.source=source;this.i=0;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var shouldYield=tryCatch(this.predicate)(x,this.i++,this.source);if(shouldYield===errorObj){return this.o.onError(shouldYield.e)}shouldYield&&this.o.onNext(x)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return FilterObservable}(ObservableBase);observableProto.filter=observableProto.where=function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg)};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(o){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){o.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){o.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},function(e){o.onError(e)},function(){o.onNext(list);o.onCompleted()})},source)}function firstOnly(x){if(x.length===0){throw new EmptyError}return x[0]}var ReduceObservable=function(__super__){inherits(ReduceObservable,__super__);function ReduceObservable(source,acc,hasSeed,seed){this.source=source;this.acc=acc;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ReduceObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new InnerObserver(observer,this))};function InnerObserver(o,parent){this.o=o;this.acc=parent.acc;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.result=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.result=tryCatch(this.acc)(this.result,x)}else{this.result=this.hasSeed?tryCatch(this.acc)(this.seed,x):x;this.hasAccumulation=true}if(this.result===errorObj){this.o.onError(this.result.e)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.hasValue&&this.o.onNext(this.result);!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);!this.hasValue&&!this.hasSeed&&this.o.onError(new EmptyError);this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return ReduceObservable}(ObservableBase);observableProto.reduce=function(accumulator){var hasSeed=false;if(arguments.length===2){hasSeed=true;var seed=arguments[1]}return new ReduceObservable(this,accumulator,hasSeed,seed)};var SomeObserver=function(__super__){inherits(SomeObserver,__super__);function SomeObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._i=0;__super__.call(this)}SomeObserver.prototype.next=function(x){var result=tryCatch(this._fn)(x,this._i++,this._s);if(result===errorObj){return this._o.onError(result.e)}if(Boolean(result)){this._o.onNext(true);this._o.onCompleted()}};SomeObserver.prototype.error=function(e){this._o.onError(e)};SomeObserver.prototype.completed=function(){this._o.onNext(false);this._o.onCompleted()};return SomeObserver}(AbstractObserver);observableProto.some=function(predicate,thisArg){var source=this,fn=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){return source.subscribe(new SomeObserver(o,fn,source))})};var IsEmptyObserver=function(__super__){inherits(IsEmptyObserver,__super__);function IsEmptyObserver(o){this._o=o;__super__.call(this)}IsEmptyObserver.prototype.next=function(){this._o.onNext(false);this._o.onCompleted()};IsEmptyObserver.prototype.error=function(e){this._o.onError(e)};IsEmptyObserver.prototype.completed=function(){this._o.onNext(true);this._o.onCompleted()};return IsEmptyObserver}(AbstractObserver);observableProto.isEmpty=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(new IsEmptyObserver(o))},source)};var EveryObserver=function(__super__){inherits(EveryObserver,__super__);function EveryObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._i=0;__super__.call(this)}EveryObserver.prototype.next=function(x){var result=tryCatch(this._fn)(x,this._i++,this._s);if(result===errorObj){return this._o.onError(result.e)}if(!Boolean(result)){this._o.onNext(false);this._o.onCompleted()}};EveryObserver.prototype.error=function(e){this._o.onError(e)};EveryObserver.prototype.completed=function(){this._o.onNext(true);this._o.onCompleted()};return EveryObserver}(AbstractObserver);observableProto.every=function(predicate,thisArg){var source=this,fn=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){return source.subscribe(new EveryObserver(o,fn,source))},this)};observableProto.includes=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(false);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){o.onNext(true);o.onCompleted()}},function(e){o.onError(e)},function(){o.onNext(false);o.onCompleted()})},this)};observableProto.contains=function(searchElement,fromIndex){observableProto.includes(searchElement,fromIndex)};observableProto.count=function(predicate,thisArg){return predicate?this.filter(predicate,thisArg).count():this.reduce(function(count){return count+1},0)};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(-1);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){o.onNext(i);o.onCompleted()}i++},function(e){o.onError(e)},function(){o.onNext(-1);o.onCompleted()})},source)};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.reduce(function(prev,curr){return prev+curr},0)};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).map(function(x){return firstOnly(x)})};var AverageObserver=function(__super__){inherits(AverageObserver,__super__);function AverageObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._c=0;this._t=0;__super__.call(this)}AverageObserver.prototype.next=function(x){if(this._fn){var r=tryCatch(this._fn)(x,this._c++,this._s);if(r===errorObj){return this._o.onError(r.e)}this._t+=r}else{this._c++;this._t+=x}};AverageObserver.prototype.error=function(e){this._o.onError(e)};AverageObserver.prototype.completed=function(){if(this._c===0){return this._o.onError(new EmptyError)}this._o.onNext(this._t/this._c);this._o.onCompleted()};return AverageObserver}(AbstractObserver);observableProto.average=function(keySelector,thisArg){var source=this,fn;if(isFunction(keySelector)){fn=bindCallback(keySelector,thisArg,3)}return new AnonymousObservable(function(o){return source.subscribe(new AverageObserver(o,fn,source))},source)};observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){o.onError(e);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(doner){o.onNext(false);o.onCompleted()}else{ql.push(x)}},function(e){o.onError(e)},function(){donel=true;if(ql.length===0){if(qr.length>0){o.onNext(false);o.onCompleted()}else if(doner){o.onNext(true);o.onCompleted()}}});(isArrayLike(second)||isIterable(second))&&(second=observableFrom(second));isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){o.onError(exception);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(donel){o.onNext(false);o.onCompleted()}else{qr.push(x)}},function(e){o.onError(e)},function(){doner=true;if(qr.length===0){if(ql.length>0){o.onNext(false);o.onCompleted()}else if(donel){o.onNext(true);o.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)},first)};observableProto.elementAt=function(index,defaultValue){if(index<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var i=index;return source.subscribe(function(x){if(i--===0){o.onNext(x);o.onCompleted()}},function(e){o.onError(e)},function(){if(defaultValue===undefined){o.onError(new ArgumentOutOfRangeError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)};observableProto.single=function(predicate,thisArg){if(isFunction(predicate)){return this.filter(predicate,thisArg).single()}var source=this;return new AnonymousObservable(function(o){var value,seenValue=false;return source.subscribe(function(x){if(seenValue){o.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},function(e){o.onError(e)},function(){o.onNext(value);o.onCompleted()})},source)};var FirstObserver=function(__super__){inherits(FirstObserver,__super__);function FirstObserver(o,obj,s){this._o=o;this._obj=obj;this._s=s;this._i=0;__super__.call(this)}FirstObserver.prototype.next=function(x){if(this._obj.predicate){var res=tryCatch(this._obj.predicate)(x,this._i++,this._s);if(res===errorObj){return this._o.onError(res.e)}if(Boolean(res)){this._o.onNext(x);this._o.onCompleted()}}else if(!this._obj.predicate){this._o.onNext(x);this._o.onCompleted()}};FirstObserver.prototype.error=function(e){this._o.onError(e)};FirstObserver.prototype.completed=function(){if(this._obj.defaultValue===undefined){this._o.onError(new EmptyError)}else{this._o.onNext(this._obj.defaultValue);this._o.onCompleted()}};return FirstObserver}(AbstractObserver);observableProto.first=function(){var obj={},source=this;if(typeof arguments[0]==="object"){obj=arguments[0]}else{obj={predicate:arguments[0],thisArg:arguments[1],defaultValue:arguments[2]}}if(isFunction(obj.predicate)){var fn=obj.predicate;obj.predicate=bindCallback(fn,obj.thisArg,3)}return new AnonymousObservable(function(o){return source.subscribe(new FirstObserver(o,obj,source))},source)};observableProto.last=function(){var obj={},source=this;if(typeof arguments[0]==="object"){obj=arguments[0]}else{obj={predicate:arguments[0],thisArg:arguments[1],defaultValue:arguments[2]}}if(isFunction(obj.predicate)){var fn=obj.predicate;obj.predicate=bindCallback(fn,obj.thisArg,3)}return new AnonymousObservable(function(o){var value,seenValue=false,i=0;return source.subscribe(function(x){if(obj.predicate){var res=tryCatch(obj.predicate)(x,i++,source);if(res===errorObj){return o.onError(res.e)}if(res){seenValue=true;value=x}}else if(!obj.predicate){seenValue=true;value=x}},function(e){o.onError(e)},function(){if(seenValue){o.onNext(value);o.onCompleted()}else if(obj.defaultValue===undefined){o.onError(new EmptyError)}else{o.onNext(obj.defaultValue);o.onCompleted()}})},source)};function findValue(source,predicate,thisArg,yieldIndex){var callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=callback(x,i,source)}catch(e){o.onError(e);return}if(shouldRun){o.onNext(yieldIndex?i:x);o.onCompleted()}else{i++}},function(e){o.onError(e)},function(){o.onNext(yieldIndex?-1:undefined);o.onCompleted()})},source)}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};observableProto.toSet=function(){if(typeof root.Set==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var s=new root.Set;return source.subscribe(function(x){s.add(x)},function(e){o.onError(e)},function(){o.onNext(s);o.onCompleted()})},source)};observableProto.toMap=function(keySelector,elementSelector){if(typeof root.Map==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){o.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){o.onError(e);return}}m.set(key,element)},function(e){o.onError(e)},function(){o.onNext(m);o.onCompleted()})},source)};var wrap=Observable.wrap=function(fn){createObservable.__generatorFunction__=fn;return createObservable;function createObservable(){return Observable.spawn.call(this,fn.apply(this,arguments))}};var spawn=Observable.spawn=function(){var gen=arguments[0],self=this,args=[];for(var i=1,len=arguments.length;i2){var args=[];for(var i=1,len=arguments.length;i0){o.onNext(q.shift())}}var subscription=combineLatestSource(this.source,this.pauser.startWith(false).distinctUntilChanged(),function(data,shouldFire){ +return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){drainQueue()}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){o.onNext(results.data)}else{q.push(results.data)}}},function(err){drainQueue();o.onError(err)},function(){drainQueue();o.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};var ControlledObservable=function(__super__){inherits(ControlledObservable,__super__);function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue,scheduler){__super__.call(this,subscribe,source);this.subject=new ControlledSubject(enableQueue,scheduler);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){return this.subject.request(numberOfItems==null?-1:numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=function(__super__){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue,scheduler){enableQueue==null&&(enableQueue=true);__super__.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=null;this.error=null;this.hasFailed=false;this.hasCompleted=false;this.scheduler=scheduler||currentThreadScheduler}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0){this.subject.onCompleted();this.disposeCurrentRequest()}else{this.queue.push(Notification.createOnCompleted())}},onError:function(error){this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0){this.subject.onError(error);this.disposeCurrentRequest()}else{this.queue.push(Notification.createOnError(error))}},onNext:function(value){if(this.requestedCount<=0){this.enableQueue&&this.queue.push(Notification.createOnNext(value))}else{this.requestedCount--===0&&this.disposeCurrentRequest();this.subject.onNext(value)}},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>0&&(numberOfItems>0||this.queue[0].kind!=="N")){var first=this.queue.shift();first.accept(this.subject);if(first.kind==="N"){numberOfItems--}else{this.disposeCurrentRequest();this.queue=[]}}}return numberOfItems},request:function(number){this.disposeCurrentRequest();var self=this;this.requestedDisposable=this.scheduler.scheduleWithState(number,function(s,i){var remaining=self._processRequest(i);var stopped=self.hasCompleted||self.hasFailed;if(!stopped&&remaining>0){self.requestedCount=remaining;return disposableCreate(function(){self.requestedCount=0})}});return this.requestedDisposable},disposeCurrentRequest:function(){if(this.requestedDisposable){this.requestedDisposable.dispose();this.requestedDisposable=null}}});return ControlledSubject}(Observable);observableProto.controlled=function(enableQueue,scheduler){if(enableQueue&&isScheduler(enableQueue)){scheduler=enableQueue;enableQueue=true}if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue,scheduler)};var StopAndWaitObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new StopAndWaitObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(1)});return this.subscription}inherits(StopAndWaitObservable,__super__);function StopAndWaitObservable(source){__super__.call(this,subscribe,source);this.source=source}var StopAndWaitObserver=function(__sub__){inherits(StopAndWaitObserver,__sub__);function StopAndWaitObserver(observer,observable,cancel){__sub__.call(this);this.observer=observer;this.observable=observable;this.cancel=cancel}var stopAndWaitObserverProto=StopAndWaitObserver.prototype;stopAndWaitObserverProto.completed=function(){this.observer.onCompleted();this.dispose()};stopAndWaitObserverProto.error=function(error){this.observer.onError(error);this.dispose()};stopAndWaitObserverProto.next=function(value){this.observer.onNext(value);var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(1)})};stopAndWaitObserverProto.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return StopAndWaitObserver}(AbstractObserver);return StopAndWaitObservable}(Observable);ControlledObservable.prototype.stopAndWait=function(){return new StopAndWaitObservable(this)};var WindowedObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new WindowedObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(self.windowSize)});return this.subscription}inherits(WindowedObservable,__super__);function WindowedObservable(source,windowSize){__super__.call(this,subscribe,source);this.source=source;this.windowSize=windowSize}var WindowedObserver=function(__sub__){inherits(WindowedObserver,__sub__);function WindowedObserver(observer,observable,cancel){this.observer=observer;this.observable=observable;this.cancel=cancel;this.received=0}var windowedObserverPrototype=WindowedObserver.prototype;windowedObserverPrototype.completed=function(){this.observer.onCompleted();this.dispose()};windowedObserverPrototype.error=function(error){this.observer.onError(error);this.dispose()};windowedObserverPrototype.next=function(value){this.observer.onNext(value);this.received=++this.received%this.observable.windowSize;if(this.received===0){var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(self.observable.windowSize)})}};windowedObserverPrototype.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return WindowedObserver}(AbstractObserver);return WindowedObservable}(Observable);ControlledObservable.prototype.windowed=function(windowSize){return new WindowedObservable(this,windowSize)};observableProto.pipe=function(dest){var source=this.pausableBuffered();function onDrain(){source.resume()}dest.addListener("drain",onDrain);source.subscribe(function(x){!dest.write(String(x))&&source.pause()},function(err){dest.emit("error",err)},function(){!dest._isStdio&&dest.end();dest.removeListener("drain",onDrain)});source.resume();return dest};observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())},source):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,windowSize,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler))};observableProto.shareReplay=function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.hasError=false}addProperties(BehaviorSubject.prototype,Observer,{getValue:function(){checkDisposed(this);if(this.hasError){throw this.error}return this.value},hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d},this)};Observable.forkJoin=function(){var allSources=[];if(Array.isArray(arguments[0])){allSources=arguments[0]}else{for(var i=0,len=arguments.length;i0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count);self(count+1,d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!=null&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){return observableTimerDateAndPeriod(dueTime.getTime(),periodOrScheduler,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)},source)}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.debounce=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)},this)};observableProto.throttle=function(dueTime,scheduler){return this.debounce(dueTime,scheduler)};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}o.onCompleted()})},source)};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){o.onNext(next.value)}}o.onCompleted()})},source)};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();now-next.interval<=duration&&res.push(next.value)}o.onNext(res);o.onCompleted()})},source)};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))},source)};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()}))},source)};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler[schedulerMethod](endTime,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.throttleFirst=function(windowDuration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var duration=+windowDuration||0;if(duration<=0){throw new RangeError("windowDuration cannot be less or equal zero.")}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext===0||now-lastOnNext>=duration){lastOnNext=now;o.onNext(x)}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.transduce=function(transducer){var source=this;function transformForObserver(o){return{"@@transducer/init":function(){return o},"@@transducer/step":function(obs,input){return obs.onNext(input)},"@@transducer/result":function(obs){return obs.onCompleted()}}}return new AnonymousObservable(function(o){var xform=transducer(transformForObserver(o));return source.subscribe(function(v){var res=tryCatch(xform["@@transducer/step"]).call(xform,o,v);if(res===errorObj){o.onError(res.e)}},function(e){o.onError(e)},function(){xform["@@transducer/result"](o)})},source)};observableProto.switchFirst=function(){var sources=this;return new AnonymousObservable(function(o){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(function(x){o.onNext(x)},function(e){o.onError(e)},function(){g.remove(innerSubscription);hasCurrent=false;isStopped&&g.length===1&&o.onCompleted()}))}},function(e){o.onError(e)},function(){isStopped=true;!hasCurrent&&g.length===1&&o.onCompleted()}));return g},this)};observableProto.flatMapFirst=observableProto.selectManyFirst=function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).switchFirst()};Rx.Observable.prototype.flatMapWithMaxConcurrent=function(limit,selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).merge(limit)};var VirtualTimeScheduler=Rx.VirtualTimeScheduler=function(__super__){function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new ArgumentOutOfRangeError}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.__subscribe).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function innerSubscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function AnonymousObservable(subscribe,parent){this.source=parent;this.__subscribe=subscribe;__super__.call(this,innerSubscribe)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result===errorObj){this.dispose();thrower(result.e)}};AutoDetachObserverPrototype.error=function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.completed=function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(){return this.m.getDisposable()};AutoDetachObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,__super__);function Subject(){__super__.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[];this.hasError=false}addProperties(Subject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(!this.isStopped){this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},onCompleted:function(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped=true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i=0;i1){for(var i=1;i=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){storage.removeItem("debug")}else{storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=storage.debug}catch(e){}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}},{"./debug":6}],6:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms