From 4a09e722653b98b58ffaa7999c9574459a60b2c8 Mon Sep 17 00:00:00 2001 From: Stephanie Chung Date: Fri, 9 May 2014 23:13:32 -0700 Subject: [PATCH] adding RxJS --- js/libs/rxjs/rx.aggregates.js | 684 ++++ js/libs/rxjs/rx.aggregates.min.js | 1 + js/libs/rxjs/rx.async.compat.js | 396 ++ js/libs/rxjs/rx.async.compat.min.js | 1 + js/libs/rxjs/rx.async.js | 328 ++ js/libs/rxjs/rx.async.min.js | 1 + js/libs/rxjs/rx.backpressure.js | 398 ++ js/libs/rxjs/rx.backpressure.min.js | 1 + js/libs/rxjs/rx.binding.js | 561 +++ js/libs/rxjs/rx.binding.min.js | 1 + js/libs/rxjs/rx.coincidence.js | 689 ++++ js/libs/rxjs/rx.coincidence.min.js | 1 + js/libs/rxjs/rx.compat.js | 4558 +++++++++++++++++++++ js/libs/rxjs/rx.compat.min.js | 2 + js/libs/rxjs/rx.experimental.js | 471 +++ js/libs/rxjs/rx.experimental.min.js | 1 + js/libs/rxjs/rx.joinpatterns.js | 415 ++ js/libs/rxjs/rx.joinpatterns.min.js | 1 + js/libs/rxjs/rx.js | 4440 +++++++++++++++++++++ js/libs/rxjs/rx.lite.compat.js | 5754 +++++++++++++++++++++++++++ js/libs/rxjs/rx.lite.compat.min.js | 2 + js/libs/rxjs/rx.lite.js | 5568 ++++++++++++++++++++++++++ js/libs/rxjs/rx.lite.min.js | 2 + js/libs/rxjs/rx.min.js | 2 + js/libs/rxjs/rx.node.js | 144 + js/libs/rxjs/rx.testing.js | 500 +++ js/libs/rxjs/rx.testing.min.js | 1 + js/libs/rxjs/rx.time.js | 1165 ++++++ js/libs/rxjs/rx.time.min.js | 1 + js/libs/rxjs/rx.virtualtime.js | 335 ++ js/libs/rxjs/rx.virtualtime.min.js | 1 + 31 files changed, 26425 insertions(+) create mode 100644 js/libs/rxjs/rx.aggregates.js create mode 100644 js/libs/rxjs/rx.aggregates.min.js create mode 100644 js/libs/rxjs/rx.async.compat.js create mode 100644 js/libs/rxjs/rx.async.compat.min.js create mode 100644 js/libs/rxjs/rx.async.js create mode 100644 js/libs/rxjs/rx.async.min.js create mode 100644 js/libs/rxjs/rx.backpressure.js create mode 100644 js/libs/rxjs/rx.backpressure.min.js create mode 100644 js/libs/rxjs/rx.binding.js create mode 100644 js/libs/rxjs/rx.binding.min.js create mode 100644 js/libs/rxjs/rx.coincidence.js create mode 100644 js/libs/rxjs/rx.coincidence.min.js create mode 100644 js/libs/rxjs/rx.compat.js create mode 100644 js/libs/rxjs/rx.compat.min.js create mode 100644 js/libs/rxjs/rx.experimental.js create mode 100644 js/libs/rxjs/rx.experimental.min.js create mode 100644 js/libs/rxjs/rx.joinpatterns.js create mode 100644 js/libs/rxjs/rx.joinpatterns.min.js create mode 100644 js/libs/rxjs/rx.js create mode 100644 js/libs/rxjs/rx.lite.compat.js create mode 100644 js/libs/rxjs/rx.lite.compat.min.js create mode 100644 js/libs/rxjs/rx.lite.js create mode 100644 js/libs/rxjs/rx.lite.min.js create mode 100644 js/libs/rxjs/rx.min.js create mode 100644 js/libs/rxjs/rx.node.js create mode 100644 js/libs/rxjs/rx.testing.js create mode 100644 js/libs/rxjs/rx.testing.min.js create mode 100644 js/libs/rxjs/rx.time.js create mode 100644 js/libs/rxjs/rx.time.min.js create mode 100644 js/libs/rxjs/rx.virtualtime.js create mode 100644 js/libs/rxjs/rx.virtualtime.min.js diff --git a/js/libs/rxjs/rx.aggregates.js b/js/libs/rxjs/rx.aggregates.js new file mode 100644 index 0000000..40a301e --- /dev/null +++ b/js/libs/rxjs/rx.aggregates.js @@ -0,0 +1,684 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + CompositeDisposable = Rx.CompositeDisposable, + AnonymousObservable = Rx.AnonymousObservable, + isEqual = Rx.internals.isEqual, + helpers = Rx.helpers, + defaultComparer = helpers.defaultComparer, + identity = helpers.identity, + subComparer = helpers.defaultSubComparer, + isPromise = helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + // Defaults + var argumentOutOfRange = 'Argument out of range', + sequenceContainsNoElements = "Sequence contains no elements."; + + function extremaBy(source, keySelector, comparer) { + return new AnonymousObservable(function (observer) { + var hasValue = false, lastKey = null, list = []; + return source.subscribe(function (x) { + var comparison, key; + try { + key = keySelector(x); + } catch (ex) { + observer.onError(ex); + return; + } + comparison = 0; + if (!hasValue) { + hasValue = true; + lastKey = key; + } else { + try { + comparison = comparer(key, lastKey); + } catch (ex1) { + observer.onError(ex1); + return; + } + } + if (comparison > 0) { + lastKey = key; + list = []; + } + if (comparison >= 0) { + list.push(x); + } + }, observer.onError.bind(observer), function () { + observer.onNext(list); + observer.onCompleted(); + }); + }); + } + + function firstOnly(x) { + if (x.length === 0) { + throw new Error(sequenceContainsNoElements); + } + 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. + * @example + * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); + * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); + * @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 seed, hasSeed, accumulator; + if (arguments.length === 2) { + seed = arguments[0]; + hasSeed = true; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * 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. + * @example + * 1 - res = source.reduce(function (acc, x) { return acc + x; }); + * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @param {Any} [seed] The initial accumulator value. + * @returns {Observable} An observable sequence containing a single element with the final accumulator value. + */ + observableProto.reduce = function (accumulator) { + var seed, hasSeed; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[1]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. + * @example + * var result = source.any(); + * var result = source.any(function (x) { return x > 3; }); + * @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 = observableProto.any = function (predicate, thisArg) { + var source = this; + return predicate ? + source.where(predicate, thisArg).any() : + new AnonymousObservable(function (observer) { + return source.subscribe(function () { + observer.onNext(true); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + observer.onNext(false); + observer.onCompleted(); + }); + }); + }; + + /** + * Determines whether an observable sequence is empty. + * + * @memberOf Observable# + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. + */ + observableProto.isEmpty = function () { + return this.any().select(function (b) { return !b; }); + }; + + /** + * Determines whether all elements of an observable sequence satisfy a condition. + * + * 1 - res = source.all(function (value) { return value.length > 3; }); + * @memberOf Observable# + * @param {Function} [predicate] A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @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 = observableProto.all = function (predicate, thisArg) { + return this.where(function (v) { + return !predicate(v); + }, thisArg).any().select(function (b) { + return !b; + }); + }; + + /** + * Determines whether an observable sequence contains a specified element with an optional equality comparer. + * @example + * 1 - res = source.contains(42); + * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); + * @param value The value to locate in the source sequence. + * @param {Function} [comparer] An equality comparer to compare elements. + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. + */ + observableProto.contains = function (value, comparer) { + comparer || (comparer = defaultComparer); + return this.where(function (v) { + return comparer(v, value); + }).any(); + }; + + /** + * 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 + * res = source.count(); + * res = source.count(function (x) { return x > 3; }); + * @param {Function} [predicate]A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. + */ + observableProto.count = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).count() : + this.aggregate(0, function (count) { + return count + 1; + }); + }; + + /** + * 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. + * @example + * var res = source.sum(); + * var res = source.sum(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. + */ + observableProto.sum = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).sum() : + this.aggregate(0, function (prev, curr) { + return prev + curr; + }); + }; + + /** + * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. + * @example + * var res = source.minBy(function (x) { return x.value; }); + * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. + */ + observableProto.minBy = function (keySelector, comparer) { + comparer || (comparer = subComparer); + 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 + * var res = source.min(); + * var res = source.min(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. + */ + observableProto.min = function (comparer) { + return this.minBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. + * @example + * var res = source.maxBy(function (x) { return x.value; }); + * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. + */ + observableProto.maxBy = function (keySelector, comparer) { + comparer || (comparer = subComparer); + return extremaBy(this, keySelector, comparer); + }; + + /** + * Returns the maximum value in an observable sequence according to the specified comparer. + * @example + * var res = source.max(); + * var res = source.max(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. + */ + observableProto.max = function (comparer) { + return this.maxBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * 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. + * @example + * var res = res = source.average(); + * var res = res = source.average(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. + */ + observableProto.average = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).average() : + this.scan({ + sum: 0, + count: 0 + }, function (prev, cur) { + return { + sum: prev.sum + cur, + count: prev.count + 1 + }; + }).finalValue().select(function (s) { + if (s.count === 0) { + throw new Error('The input sequence was empty'); + } + return s.sum / s.count; + }); + }; + + function sequenceEqualArray(first, second, comparer) { + return new AnonymousObservable(function (observer) { + var count = 0, len = second.length; + return first.subscribe(function (value) { + var equal = false; + try { + if (count < len) { + equal = comparer(value, second[count++]); + } + } catch (e) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(count === len); + observer.onCompleted(); + }); + }); + } + + /** + * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. + * + * @example + * var res = res = source.sequenceEqual([1,2,3]); + * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); + * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); + * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); + * @param {Observable} second Second observable sequence or array to compare. + * @param {Function} [comparer] Comparer used to compare elements of both sequences. + * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. + */ + observableProto.sequenceEqual = function (second, comparer) { + var first = this; + comparer || (comparer = defaultComparer); + if (Array.isArray(second)) { + return sequenceEqualArray(first, second, comparer); + } + return new AnonymousObservable(function (observer) { + 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) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (doner) { + observer.onNext(false); + observer.onCompleted(); + } else { + ql.push(x); + } + }, observer.onError.bind(observer), function () { + donel = true; + if (ql.length === 0) { + if (qr.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (doner) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + + isPromise(second) && (second = observableFromPromise(second)); + var subscription2 = second.subscribe(function (x) { + var equal, v; + if (ql.length > 0) { + v = ql.shift(); + try { + equal = comparer(v, x); + } catch (exception) { + observer.onError(exception); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (donel) { + observer.onNext(false); + observer.onCompleted(); + } else { + qr.push(x); + } + }, observer.onError.bind(observer), function () { + doner = true; + if (qr.length === 0) { + if (ql.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (donel) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + return new CompositeDisposable(subscription1, subscription2); + }); + }; + + function elementAtOrDefault(source, index, hasDefault, defaultValue) { + if (index < 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var i = index; + return source.subscribe(function (x) { + if (i === 0) { + observer.onNext(x); + observer.onCompleted(); + } + i--; + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(argumentOutOfRange)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * 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. + */ + observableProto.elementAtOrDefault = function (index, defaultValue) { + return elementAtOrDefault(this, index, true, defaultValue); + }; + + function singleOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + if (seenValue) { + observer.onError(new Error('Sequence contains more than one element')); + } else { + value = x; + seenValue = true; + } + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * 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. + * @example + * var res = res = source.single(); + * var res = res = source.single(function (x) { return x === 42; }); + * @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 ? + 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? + this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : + singleOrDefaultAsync(this, true, defaultValue) + }; + function firstOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + observer.onNext(x); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * 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. + * @example + * var res = res = source.firstOrDefault(); + * var res = res = source.firstOrDefault(function (x) { return x > 3; }); + * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); + * var res = source.firstOrDefault(null, 0); + * @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) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + value = x; + seenValue = true; + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. + * @example + * var res = source.last(); + * var res = source.last(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 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. + * @example + * var res = source.lastOrDefault(); + * var res = source.lastOrDefault(function (x) { return x > 3; }); + * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); + * var res = source.lastOrDefault(null, 0); + * @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); + }; + + function findValue (source, predicate, thisArg, yieldIndex) { + return new AnonymousObservable(function (observer) { + var i = 0; + return source.subscribe(function (x) { + var shouldRun; + try { + shouldRun = predicate.call(thisArg, x, i, source); + } catch(e) { + observer.onError(e); + return; + } + if (shouldRun) { + observer.onNext(yieldIndex ? i : x); + observer.onCompleted(); + } else { + i++; + } + }, observer.onError.bind(observer), function () { + observer.onNext(yieldIndex ? -1 : undefined); + observer.onCompleted(); + }); + }); + } + + /** + * 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. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. + */ + 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. + * @param {Function} predicate The predicate that defines the conditions of the element to search for. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. + */ + observableProto.findIndex = function (predicate, thisArg) { + return findValue(this, predicate, thisArg, true); + }; + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.aggregates.min.js b/js/libs/rxjs/rx.aggregates.min.js new file mode 100644 index 0000000..a69aaac --- /dev/null +++ b/js/libs/rxjs/rx.aggregates.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b,c){return new p(function(d){var e=!1,f=null,g=[];return a.subscribe(function(a){var h,i;try{i=b(a)}catch(j){return d.onError(j),void 0}if(h=0,e)try{h=c(i,f)}catch(k){return d.onError(k),void 0}else e=!0,f=i;h>0&&(f=i,g=[]),h>=0&&g.push(a)},d.onError.bind(d),function(){d.onNext(g),d.onCompleted()})})}function f(a){if(0===a.length)throw new Error(x);return a[0]}function g(a,b,c){return new p(function(d){var e=0,f=b.length;return a.subscribe(function(a){var g=!1;try{f>e&&(g=c(a,b[e++]))}catch(h){return d.onError(h),void 0}g||(d.onNext(!1),d.onCompleted())},d.onError.bind(d),function(){d.onNext(e===f),d.onCompleted()})})}function h(a,b,c,d){if(0>b)throw new Error(w);return new p(function(e){var f=b;return a.subscribe(function(a){0===f&&(e.onNext(a),e.onCompleted()),f--},e.onError.bind(e),function(){c?(e.onNext(d),e.onCompleted()):e.onError(new Error(w))})})}function i(a,b,c){return new p(function(d){var e=c,f=!1;return a.subscribe(function(a){f?d.onError(new Error("Sequence contains more than one element")):(e=a,f=!0)},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(x))})})}function j(a,b,c){return new p(function(d){return a.subscribe(function(a){d.onNext(a),d.onCompleted()},d.onError.bind(d),function(){b?(d.onNext(c),d.onCompleted()):d.onError(new Error(x))})})}function k(a,b,c){return new p(function(d){var e=c,f=!1;return a.subscribe(function(a){e=a,f=!0},d.onError.bind(d),function(){f||b?(d.onNext(e),d.onCompleted()):d.onError(new Error(x))})})}function l(a,b,c,e){return new p(function(f){var g=0;return a.subscribe(function(d){var h;try{h=b.call(c,d,g,a)}catch(i){return f.onError(i),void 0}h?(f.onNext(e?g:d),f.onCompleted()):g++},f.onError.bind(f),function(){f.onNext(e?-1:d),f.onCompleted()})})}var m=c.Observable,n=m.prototype,o=c.CompositeDisposable,p=c.AnonymousObservable,q=(c.internals.isEqual,c.helpers),r=q.defaultComparer,s=q.identity,t=q.defaultSubComparer,u=q.isPromise,v=m.fromPromise,w="Argument out of range",x="Sequence contains no elements.";return n.aggregate=function(){var a,b,c;return 2===arguments.length?(a=arguments[0],b=!0,c=arguments[1]):c=arguments[0],b?this.scan(a,c).startWith(a).finalValue():this.scan(c).finalValue()},n.reduce=function(a){var b,c;return 2===arguments.length&&(c=!0,b=arguments[1]),c?this.scan(b,a).startWith(b).finalValue():this.scan(a).finalValue()},n.some=n.any=function(a,b){var c=this;return a?c.where(a,b).any():new p(function(a){return c.subscribe(function(){a.onNext(!0),a.onCompleted()},a.onError.bind(a),function(){a.onNext(!1),a.onCompleted()})})},n.isEmpty=function(){return this.any().select(function(a){return!a})},n.every=n.all=function(a,b){return this.where(function(b){return!a(b)},b).any().select(function(a){return!a})},n.contains=function(a,b){return b||(b=r),this.where(function(c){return b(c,a)}).any()},n.count=function(a,b){return a?this.where(a,b).count():this.aggregate(0,function(a){return a+1})},n.sum=function(a,b){return a?this.select(a,b).sum():this.aggregate(0,function(a,b){return a+b})},n.minBy=function(a,b){return b||(b=t),e(this,a,function(a,c){return-1*b(a,c)})},n.min=function(a){return this.minBy(s,a).select(function(a){return f(a)})},n.maxBy=function(a,b){return b||(b=t),e(this,a,b)},n.max=function(a){return this.maxBy(s,a).select(function(a){return f(a)})},n.average=function(a,b){return a?this.select(a,b).average():this.scan({sum:0,count:0},function(a,b){return{sum:a.sum+b,count:a.count+1}}).finalValue().select(function(a){if(0===a.count)throw new Error("The input sequence was empty");return a.sum/a.count})},n.sequenceEqual=function(a,b){var c=this;return b||(b=r),Array.isArray(a)?g(c,a,b):new p(function(d){var e=!1,f=!1,g=[],h=[],i=c.subscribe(function(a){var c,e;if(h.length>0){e=h.shift();try{c=b(e,a)}catch(i){return d.onError(i),void 0}c||(d.onNext(!1),d.onCompleted())}else f?(d.onNext(!1),d.onCompleted()):g.push(a)},d.onError.bind(d),function(){e=!0,0===g.length&&(h.length>0?(d.onNext(!1),d.onCompleted()):f&&(d.onNext(!0),d.onCompleted()))});u(a)&&(a=v(a));var j=a.subscribe(function(a){var c,f;if(g.length>0){f=g.shift();try{c=b(f,a)}catch(i){return d.onError(i),void 0}c||(d.onNext(!1),d.onCompleted())}else e?(d.onNext(!1),d.onCompleted()):h.push(a)},d.onError.bind(d),function(){f=!0,0===h.length&&(g.length>0?(d.onNext(!1),d.onCompleted()):e&&(d.onNext(!0),d.onCompleted()))});return new o(i,j)})},n.elementAt=function(a){return h(this,a,!1)},n.elementAtOrDefault=function(a,b){return h(this,a,!0,b)},n.single=function(a,b){return a?this.where(a,b).single():i(this,!1)},n.singleOrDefault=function(a,b,c){return a?this.where(a,c).singleOrDefault(null,b):i(this,!0,b)},n.first=function(a,b){return a?this.where(a,b).first():j(this,!1)},n.firstOrDefault=function(a,b){return a?this.where(a).firstOrDefault(null,b):j(this,!0,b)},n.last=function(a,b){return a?this.where(a,b).last():k(this,!1)},n.lastOrDefault=function(a,b,c){return a?this.where(a,c).lastOrDefault(null,b):k(this,!0,b)},n.find=function(a,b){return l(this,a,b,!1)},n.findIndex=function(a,b){return l(this,a,b,!0)},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.async.compat.js b/js/libs/rxjs/rx.async.compat.js new file mode 100644 index 0000000..f0397b0 --- /dev/null +++ b/js/libs/rxjs/rx.async.compat.js @@ -0,0 +1,396 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + slice = Array.prototype.slice; + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * var res = Rx.Observable.start(function () { console.log('hello'); }); + * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); + * + * @param {Function} func Function to run asynchronously. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + * + * Remarks + * * The function is called immediately, not during the subscription of the resulting sequence. + * * Multiple subscriptions to the resulting sequence can observe the function's result. + */ + Observable.start = function (func, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * 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. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, scheduler, context) { + scheduler || (scheduler = timeoutScheduler); + return function () { + var args = arguments, + subject = new AsyncSubject(); + + scheduler.schedule(function () { + var result; + try { + result = func.apply(context, args); + } catch (e) { + subject.onError(e); + return; + } + subject.onNext(result); + subject.onCompleted(); + }); + 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 {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + /** + * 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 {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + function fixEvent(event) { + var stopPropagation = function () { + this.cancelBubble = true; + }; + + var preventDefault = function () { + this.bubbledKeyCode = this.keyCode; + if (this.ctrlKey) { + try { + this.keyCode = 0; + } catch (e) { } + } + this.defaultPrevented = true; + this.returnValue = false; + this.modified = true; + }; + + event || (event = root.event); + if (!event.target) { + event.target = event.target || event.srcElement; + + if (event.type == 'mouseover') { + event.relatedTarget = event.fromElement; + } + if (event.type == 'mouseout') { + event.relatedTarget = event.toElement; + } + // Adding stopPropogation and preventDefault to IE + if (!event.stopPropagation){ + event.stopPropagation = stopPropagation; + event.preventDefault = preventDefault; + } + // Normalize key events + switch(event.type){ + case 'keypress': + var c = ('charCode' in event ? event.charCode : event.keyCode); + if (c == 10) { + c = 0; + event.keyCode = 13; + } else if (c == 13 || c == 27) { + c = 0; + } else if (c == 3) { + c = 99; + } + event.charCode = c; + event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; + break; + } + } + + return event; + } + + function createListener (element, name, handler) { + // Node.js specific + if (element.addListener) { + element.addListener(name, handler); + return disposableCreate(function () { + element.removeListener(name, handler); + }); + } + // Standards compliant + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + if (element.attachEvent) { + // IE Specific + var innerHandler = function (event) { + handler(fixEvent(event)); + }; + element.attachEvent('on' + name, innerHandler); + return disposableCreate(function () { + element.detachEvent('on' + name, innerHandler); + }); + } + // Level 1 DOM Events + element['on' + name] = handler; + return disposableCreate(function () { + element['on' + name] = null; + }); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (typeof el.item === 'function' && typeof el.length === 'number') { + 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)); + } + + return disposables; + } + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + /** + * 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. + * @returns {Observable} An observable sequence of events from the specified element and the specified event. + */ + Observable.fromEvent = function (element, eventName, selector) { + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName); }, + function (h) { Ember.removeListener(element, eventName); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).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. + * @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) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (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. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.async.compat.min.js b/js/libs/rxjs/rx.async.compat.min.js new file mode 100644 index 0000000..f9cb12c --- /dev/null +++ b/js/libs/rxjs/rx.async.compat.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(b){var c=function(){this.cancelBubble=!0},d=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(b||(b=a.event),!b.target)switch(b.target=b.target||b.srcElement,"mouseover"==b.type&&(b.relatedTarget=b.fromElement),"mouseout"==b.type&&(b.relatedTarget=b.toElement),b.stopPropagation||(b.stopPropagation=c,b.preventDefault=d),b.type){case"keypress":var e="charCode"in b?b.charCode:b.keyCode;10==e?(e=0,b.keyCode=13):13==e||27==e?e=0:3==e&&(e=99),b.charCode=e,b.keyChar=b.charCode?String.fromCharCode(b.charCode):""}return b}function e(a,b,c){if(a.addListener)return a.addListener(b,c),l(function(){a.removeListener(b,c)});if(a.addEventListener)return a.addEventListener(b,c,!1),l(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var e=function(a){c(d(a))};return a.attachEvent("on"+b,e),l(function(){a.detachEvent("on"+b,e)})}return a["on"+b]=c,l(function(){a["on"+b]=null})}function f(a,b,c){var d=new m;if("function"==typeof a.item&&"number"==typeof a.length)for(var g=0,h=a.length;h>g;g++)d.add(f(a.item(g),b,c));else a&&d.add(e(a,b,c));return d}var g=c.Observable,h=(g.prototype,g.fromPromise),i=g.throwException,j=c.AnonymousObservable,k=c.AsyncSubject,l=c.Disposable.create,m=c.CompositeDisposable,n=c.Scheduler.immediate,o=c.Scheduler.timeout,p=Array.prototype.slice;g.start=function(a,b,c){return q(a,b,c)()};var q=g.toAsync=function(a,b,c){return b||(b=o),function(){var d=arguments,e=new k;return b.schedule(function(){var b;try{b=a.apply(c,d)}catch(f){return e.onError(f),void 0}e.onNext(b),e.onCompleted()}),e.asObservable()}};g.fromCallback=function(a,b,c,d){return b||(b=n),function(){var e=p.call(arguments,0);return new j(function(f){return b.schedule(function(){function b(a){var b=a;if(d)try{b=d(arguments)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}},g.fromNodeCallback=function(a,b,c,d){return b||(b=n),function(){var e=p.call(arguments,0);return new j(function(f){return b.schedule(function(){function b(a){if(a)return f.onError(a),void 0;var b=p.call(arguments,1);if(d)try{b=d(b)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}};var r=a.angular&&angular.element?angular.element:a.jQuery?a.jQuery:a.Zepto?a.Zepto:null,s=!!a.Ember&&"function"==typeof a.Ember.addListener;g.fromEvent=function(a,b,c){if(s)return t(function(){Ember.addListener(a,b)},function(){Ember.removeListener(a,b)},c);if(r){var d=r(a);return t(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}return new j(function(d){return f(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)})}).publish().refCount()};var t=g.fromEventPattern=function(a,b,c){return new j(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)}var f=a(e);return l(function(){b&&b(e,f)})}).publish().refCount()};return g.startAsync=function(a){var b;try{b=a()}catch(c){return i(c)}return h(b)},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.async.js b/js/libs/rxjs/rx.async.js new file mode 100644 index 0000000..835e8e5 --- /dev/null +++ b/js/libs/rxjs/rx.async.js @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + slice = Array.prototype.slice; + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * var res = Rx.Observable.start(function () { console.log('hello'); }); + * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); + * + * @param {Function} func Function to run asynchronously. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + * + * Remarks + * * The function is called immediately, not during the subscription of the resulting sequence. + * * Multiple subscriptions to the resulting sequence can observe the function's result. + */ + Observable.start = function (func, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * 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. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, scheduler, context) { + scheduler || (scheduler = timeoutScheduler); + return function () { + var args = arguments, + subject = new AsyncSubject(); + + scheduler.schedule(function () { + var result; + try { + result = func.apply(context, args); + } catch (e) { + subject.onError(e); + return; + } + subject.onNext(result); + subject.onCompleted(); + }); + 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 {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + /** + * 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 {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + function createListener (element, name, handler) { + // Node.js specific + if (element.addListener) { + element.addListener(name, handler); + return disposableCreate(function () { + element.removeListener(name, handler); + }); + } + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + throw new Error('No listener found'); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (typeof el.item === 'function' && typeof el.length === 'number') { + 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)); + } + + return disposables; + } + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + /** + * 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. + * @returns {Observable} An observable sequence of events from the specified element and the specified event. + */ + Observable.fromEvent = function (element, eventName, selector) { + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName); }, + function (h) { Ember.removeListener(element, eventName); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).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. + * @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) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (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. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.async.min.js b/js/libs/rxjs/rx.async.min.js new file mode 100644 index 0000000..b38abd2 --- /dev/null +++ b/js/libs/rxjs/rx.async.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b,c){if(a.addListener)return a.addListener(b,c),k(function(){a.removeListener(b,c)});if(a.addEventListener)return a.addEventListener(b,c,!1),k(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function e(a,b,c){var f=new l;if("function"==typeof a.item&&"number"==typeof a.length)for(var g=0,h=a.length;h>g;g++)f.add(e(a.item(g),b,c));else a&&f.add(d(a,b,c));return f}var f=c.Observable,g=(f.prototype,f.fromPromise),h=f.throwException,i=c.AnonymousObservable,j=c.AsyncSubject,k=c.Disposable.create,l=c.CompositeDisposable,m=c.Scheduler.immediate,n=c.Scheduler.timeout,o=Array.prototype.slice;f.start=function(a,b,c){return p(a,b,c)()};var p=f.toAsync=function(a,b,c){return b||(b=n),function(){var d=arguments,e=new j;return b.schedule(function(){var b;try{b=a.apply(c,d)}catch(f){return e.onError(f),void 0}e.onNext(b),e.onCompleted()}),e.asObservable()}};f.fromCallback=function(a,b,c,d){return b||(b=m),function(){var e=o.call(arguments,0);return new i(function(f){return b.schedule(function(){function b(a){var b=a;if(d)try{b=d(arguments)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}},f.fromNodeCallback=function(a,b,c,d){return b||(b=m),function(){var e=o.call(arguments,0);return new i(function(f){return b.schedule(function(){function b(a){if(a)return f.onError(a),void 0;var b=o.call(arguments,1);if(d)try{b=d(b)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}};var q=a.angular&&angular.element?angular.element:a.jQuery?a.jQuery:a.Zepto?a.Zepto:null,r=!!a.Ember&&"function"==typeof a.Ember.addListener;f.fromEvent=function(a,b,c){if(r)return s(function(){Ember.addListener(a,b)},function(){Ember.removeListener(a,b)},c);if(q){var d=q(a);return s(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}return new i(function(d){return e(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)})}).publish().refCount()};var s=f.fromEventPattern=function(a,b,c){return new i(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)}var f=a(e);return k(function(){b&&b(e,f)})}).publish().refCount()};return f.startAsync=function(a){var b;try{b=a()}catch(c){return h(c)}return g(b)},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.backpressure.js b/js/libs/rxjs/rx.backpressure.js new file mode 100644 index 0000000..40dc078 --- /dev/null +++ b/js/libs/rxjs/rx.backpressure.js @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // References + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + CompositeDisposable = Rx.CompositeDisposable, + Subject = Rx.Subject, + Observer = Rx.Observer, + disposableEmpty = Rx.Disposable.empty, + disposableCreate = Rx.Disposable.create, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + timeoutScheduler = Rx.Scheduler.timeout, + identity = Rx.helpers.identity; + + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer) + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * 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 {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (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.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.backpressure.min.js b/js/libs/rxjs/rx.backpressure.min.js new file mode 100644 index 0000000..b8eb766 --- /dev/null +++ b/js/libs/rxjs/rx.backpressure.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(){if(this.isDisposed)throw new Error(q)}function e(a,b,c){return new h(function(d){function e(a,b){k[b]=a;var e;if(g[b]=!0,h||(h=g.every(p))){try{e=c.apply(null,k)}catch(f){return d.onError(f),void 0}d.onNext(e)}else j&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,j=!1,k=new Array(f);return new i(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){j=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var f=c.Observable,g=f.prototype,h=c.AnonymousObservable,i=c.CompositeDisposable,j=c.Subject,k=c.Observer,l=c.Disposable.empty,m=c.Disposable.create,n=c.internals.inherits,o=c.internals.addProperties,p=(c.Scheduler.timeout,c.helpers.identity),q="Object has been disposed",r=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=l,e=this.subject.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=l)});return new i(c,d,e)}function c(c,d){this.source=c,this.subject=d||new j,this.isPaused=!0,a.call(this,b)}return n(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(f);g.pausable=function(a){return new r(this,a)};var s=function(a){function b(a){var b=[],c=!0,d=e(this.source,this.subject.distinctUntilChanged(),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(d){if(d.shouldFire&&c&&a.onNext(d.data),d.shouldFire&&!c){for(;b.length>0;)a.onNext(b.shift());c=!0}else d.shouldFire||c?!d.shouldFire&&c&&(c=!1):b.push(d.data)},a.onError.bind(a),a.onCompleted.bind(a));return this.subject.onNext(!1),d}function c(c,d){this.source=c,this.subject=d||new j,this.isPaused=!0,a.call(this,b)}return n(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(f);g.pausableBuffered=function(a){return new s(this,a)},g.controlled=function(a){return null==a&&(a=!0),new t(this,a)};var t=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new u(d),this.source=c.multicast(this.subject).refCount()}return n(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(f),u=c.ControlledSubject=function(a){function b(a){return this.subject.subscribe(a)}function c(c){null==c&&(c=!0),a.call(this,b),this.subject=new j,this.enableQueue=c,this.queue=c?[]:null,this.requestedCount=0,this.requestedDisposable=l,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=l}return n(c,a),o(c.prototype,k,{onCompleted:function(){d.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){d.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){d.call(this);var b=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),b=!0),b&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=l):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=l),{numberOfItems:a,returnValue:!1}},request:function(a){d.call(this),this.disposeCurrentRequest();var b=this,c=this._processRequest(a);return a=c.numberOfItems,c.returnValue?l:(this.requestedCount=a,this.requestedDisposable=m(function(){b.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=l},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),c}(f);return c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.binding.js b/js/libs/rxjs/rx.binding.js new file mode 100644 index 0000000..98b2528 --- /dev/null +++ b/js/libs/rxjs/rx.binding.js @@ -0,0 +1,561 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + Subject = Rx.Subject, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + ScheduledObserver = Rx.internals.ScheduledObserver, + disposableCreate = Rx.Disposable.create, + disposableEmpty = Rx.Disposable.empty, + CompositeDisposable = Rx.CompositeDisposable, + currentThreadScheduler = Rx.Scheduler.currentThread, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties; + + // Utilities + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { + if (this.isDisposed) { + throw new Error(objectDisposed); + } + } + + /** + * 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 + * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. + * + * @example + * 1 - res = source.multicast(observable); + * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); + * + * @param {Function|Subject} subjectOrSubjectSelector + * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + * Or: + * Subject to push source elements into. + * + * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + 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. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _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(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + /** @private */ + var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { + inherits(ConnectableObservable, _super); + + /** + * @constructor + * @private + */ + function ConnectableObservable(source, subject) { + var state = { + subject: subject, + source: source.asObservable(), + hasSubscription: false, + subscription: null + }; + + this.connect = function () { + if (!state.hasSubscription) { + state.hasSubscription = true; + state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { + state.hasSubscription = false; + })); + } + return state.subscription; + }; + + function subscribe(observer) { + return state.subject.subscribe(observer); + } + + _super.call(this, subscribe); + } + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.connect = function () { return this.connect(); }; + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription = null, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect, subscription; + count++; + shouldConnect = count === 1; + subscription = source.subscribe(observer); + if (shouldConnect) { + connectableSubscription = source.connect(); + } + return disposableCreate(function () { + subscription.dispose(); + count--; + if (count === 0) { + connectableSubscription.dispose(); + } + }); + }); + }; + + return ConnectableObservable; + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.binding.min.js b/js/libs/rxjs/rx.binding.min.js new file mode 100644 index 0000000..28e6b1d --- /dev/null +++ b/js/libs/rxjs/rx.binding.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(){if(this.isDisposed)throw new Error(r)}var e=c.Observable,f=e.prototype,g=c.AnonymousObservable,h=c.Subject,i=c.AsyncSubject,j=c.Observer,k=c.internals.ScheduledObserver,l=c.Disposable.create,m=c.Disposable.empty,n=c.CompositeDisposable,o=c.Scheduler.currentThread,p=c.internals.inherits,q=c.internals.addProperties,r="Object has been disposed";f.multicast=function(a,b){var c=this;return"function"==typeof a?new g(function(d){var e=c.multicast(a());return new n(b(e).subscribe(d),e.connect())}):new v(c,a)},f.publish=function(a){return a?this.multicast(function(){return new h},a):this.multicast(new h)},f.share=function(){return this.publish(null).refCount()},f.publishLast=function(a){return a?this.multicast(function(){return new i},a):this.multicast(new i)},f.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new t(b)},a):this.multicast(new t(a))},f.shareValue=function(a){return this.publishValue(a).refCount()},f.replay=function(a,b,c,d){return a?this.multicast(function(){return new u(b,c,d)},a):this.multicast(new u(b,c,d))},f.replayWhileObserved=function(a,b,c){return this.replay(null,a,b,c).refCount()};var s=function(a,b){this.subject=a,this.observer=b};s.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var t=c.BehaviorSubject=function(a){function b(a){if(d.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new s(this,a);var b=this.exception;return b?a.onError(b):a.onCompleted(),m}function c(c){a.call(this,b),this.value=c,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return p(c,a),q(c.prototype,j,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(d.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var b=0,c=a.length;c>b;b++)a[b].onCompleted();this.observers=[]}},onError:function(a){if(d.call(this),!this.isStopped){var b=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var c=0,e=b.length;e>c;c++)b[c].onError(a);this.observers=[]}},onNext:function(a){if(d.call(this),!this.isStopped){this.value=a;for(var b=this.observers.slice(0),c=0,e=b.length;e>c;c++)b[c].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),c}(e),u=c.ReplaySubject=function(a){function b(a,b){this.subject=a,this.observer=b}function c(a){var c=new k(this.scheduler,a),e=new b(this,c);d.call(this),this._trim(this.scheduler.now()),this.observers.push(c);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)c.onNext(this.q[g].value);return this.hasError?(f++,c.onError(this.error)):this.isStopped&&(f++,c.onCompleted()),c.ensureActive(f),e}function e(b,d,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==d?Number.MAX_VALUE:d,this.scheduler=e||o,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,c)}return b.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},p(e,a),q(e.prototype,j,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var b;if(d.call(this),!this.isStopped){var c=this.scheduler.now();this.q.push({interval:c,value:a}),this._trim(c);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)b=e[f],b.onNext(a),b.ensureActive()}},onError:function(a){var b;if(d.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var c=this.scheduler.now();this._trim(c);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)b=e[f],b.onError(a),b.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(d.call(this),!this.isStopped){this.isStopped=!0;var b=this.scheduler.now();this._trim(b);for(var c=this.observers.slice(0),e=0,f=c.length;f>e;e++)a=c[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(e),v=c.ConnectableObservable=function(a){function b(b,c){function d(a){return e.subject.subscribe(a)}var e={subject:c,source:b.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return e.hasSubscription||(e.hasSubscription=!0,e.subscription=new n(e.source.subscribe(e.subject),l(function(){e.hasSubscription=!1}))),e.subscription},a.call(this,d)}return p(b,a),b.prototype.connect=function(){return this.connect()},b.prototype.refCount=function(){var a=null,b=0,c=this;return new g(function(d){var e,f;return b++,e=1===b,f=c.subscribe(d),e&&(a=c.connect()),l(function(){f.dispose(),b--,0===b&&a.dispose()})})},b}(e);return c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.coincidence.js b/js/libs/rxjs/rx.coincidence.js new file mode 100644 index 0000000..aee03b1 --- /dev/null +++ b/js/libs/rxjs/rx.coincidence.js @@ -0,0 +1,689 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + var Observable = Rx.Observable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + SerialDisposable = Rx.SerialDisposable, + Subject = Rx.Subject, + observableProto = Observable.prototype, + observableEmpty = Observable.empty, + AnonymousObservable = Rx.AnonymousObservable, + observerCreate = Rx.Observer.create, + addRef = Rx.internals.addRef, + defaultComparer = Rx.internals.isEqual, + noop = Rx.helpers.noop; + + // Real Dictionary + 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]; + var noSuchkey = "no such key"; + var 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 obj.getTime(); + } + + if (obj.getHashCode) { + return obj.getHashCode(); + } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + } ()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + // Dictionary implementation + + var Dictionary = function (capacity, comparer) { + if (capacity < 0) { + throw new Error('out of range') + } + if (capacity > 0) { + this._initialize(capacity); + } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + }; + + Dictionary.prototype._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; + }; + Dictionary.prototype.count = function () { + return this.size; + }; + Dictionary.prototype.add = function (key, value) { + return this._insert(key, value, true); + }; + Dictionary.prototype._insert = function (key, value, add) { + if (!this.buckets) { + this._initialize(0); + } + var index3; + var num = getHashCode(key) & 2147483647; + var 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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + var index1 = num % this.buckets.length; + var 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; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.count = function () { + return this.size - this.freeCount; + }; + + Dictionary.prototype.tryGetValue = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + return undefined; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + throw new Error(noSuchkey); + }; + + Dictionary.prototype.set = function (key, value) { + this._insert(key, value, false); + }; + + Dictionary.prototype.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + leftDone = false, + leftId = 0, + leftMap = new Dictionary(), + rightDone = false, + rightId = 0, + rightMap = new Dictionary(); + group.add(left.subscribe(function (value) { + var duration, + expire, + id = leftId++, + md = new SingleAssignmentDisposable(), + result, + values; + leftMap.add(id, value); + group.add(md); + expire = function () { + if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = rightMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(value, values[i]); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + leftDone = true; + if (rightDone || leftMap.count() === 0) { + observer.onCompleted(); + } + })); + group.add(right.subscribe(function (value) { + var duration, + expire, + id = rightId++, + md = new SingleAssignmentDisposable(), + result, + values; + rightMap.add(id, value); + group.add(md); + expire = function () { + if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = rightDurationSelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = leftMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(values[i], value); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + rightDone = true; + if (leftDone || rightMap.count() === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var nothing = function () {}; + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(); + var rightMap = new Dictionary(); + var leftID = 0; + var rightID = 0; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftID++; + leftMap.add(id, s); + var i, len, leftValues, rightValues; + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(result); + + rightValues = rightMap.getValues(); + for (i = 0, len = rightValues.length; i < len; i++) { + s.onNext(rightValues[i]); + } + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + if (leftMap.remove(id)) { + s.onCompleted(); + } + + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + observer.onCompleted.bind(observer))); + + group.add(right.subscribe( + function (value) { + var leftValues, i, len; + 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) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onNext(value); + } + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + })); + + return r; + }); + }; + + /** + * 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(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector 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} [windowClosingSelector] 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.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.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, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.coincidence.min.js b/js/libs/rxjs/rx.coincidence.min.js new file mode 100644 index 0000000..3079bdd --- /dev/null +++ b/js/libs/rxjs/rx.coincidence.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a){if(a&!1)return 2===a;for(var b=Math.sqrt(a),c=3;b>=c;){if(a%c===0)return!1;c+=2}return!0}function f(a){var b,c,d;for(b=0;b=a)return c;for(d=1|a;dc;c++){var e=a.charCodeAt(c);b=(b<<5)-b+e,b&=b}return b}function h(a){var b=668265261;return a=61^a^a>>>16,a+=a<<3,a^=a>>>4,a*=b,a^=a>>>15}function i(){return{key:null,value:null,next:0,hashCode:0}}function j(a,b){return a.groupJoin(this,b,function(){return t()},function(a,b){return b})}function k(a){var b=this;return new u(function(c){var d=new r,e=new n,f=new o(e);return c.onNext(v(d,f)),e.add(b.subscribe(function(a){d.onNext(a)},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),e.add(a.subscribe(function(){d.onCompleted(),d=new r,c.onNext(v(d,f))},function(a){d.onError(a),c.onError(a)},function(){d.onCompleted(),c.onCompleted()})),f})}function l(a){var b=this;return new u(function(c){var d,e=new q,f=new n(e),g=new o(f),h=new r;return c.onNext(v(h,g)),f.add(b.subscribe(function(a){h.onNext(a)},function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),c.onCompleted()})),d=function(){var b,f;try{f=a()}catch(i){return c.onError(i),void 0}b=new p,e.setDisposable(b),b.setDisposable(f.take(1).subscribe(x,function(a){h.onError(a),c.onError(a)},function(){h.onCompleted(),h=new r,c.onNext(v(h,g)),d()}))},d(),g})}var m=c.Observable,n=c.CompositeDisposable,o=c.RefCountDisposable,p=c.SingleAssignmentDisposable,q=c.SerialDisposable,r=c.Subject,s=m.prototype,t=m.empty,u=c.AnonymousObservable,v=(c.Observer.create,c.internals.addRef),w=c.internals.isEqual,x=c.helpers.noop,y=[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],z="no such key",A="duplicate key",B=function(){var a=0;return function(b){if(null==b)throw new Error(z);if("string"==typeof b)return g(b);if("number"==typeof b)return h(b);if("boolean"==typeof b)return b===!0?1:0;if(b instanceof Date)return b.getTime();if(b.getHashCode)return b.getHashCode();var c=17*a++;return b.getHashCode=function(){return c},c}}(),C=function(a,b){if(0>a)throw new Error("out of range");a>0&&this._initialize(a),this.comparer=b||w,this.freeCount=0,this.size=0,this.freeList=-1};return C.prototype._initialize=function(a){var b,c=f(a);for(this.buckets=new Array(c),this.entries=new Array(c),b=0;c>b;b++)this.buckets[b]=-1,this.entries[b]=i();this.freeList=-1},C.prototype.count=function(){return this.size},C.prototype.add=function(a,b){return this._insert(a,b,!0)},C.prototype._insert=function(a,b,c){this.buckets||this._initialize(0);for(var d,e=2147483647&B(a),f=e%this.buckets.length,g=this.buckets[f];g>=0;g=this.entries[g].next)if(this.entries[g].hashCode===e&&this.comparer(this.entries[g].key,a)){if(c)throw new Error(A);return this.entries[g].value=b,void 0}this.freeCount>0?(d=this.freeList,this.freeList=this.entries[d].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),f=e%this.buckets.length),d=this.size,++this.size),this.entries[d].hashCode=e,this.entries[d].next=this.buckets[f],this.entries[d].key=a,this.entries[d].value=b,this.buckets[f]=d},C.prototype._resize=function(){var a=f(2*this.size),b=new Array(a);for(d=0;dd;++d)c[d]=i();for(var e=0;e=0;e=this.entries[e].next){if(this.entries[e].hashCode===b&&this.comparer(this.entries[e].key,a))return 0>d?this.buckets[c]=this.entries[e].next:this.entries[d].next=this.entries[e].next,this.entries[e].hashCode=-1,this.entries[e].next=this.freeList,this.entries[e].key=null,this.entries[e].value=null,this.freeList=e,++this.freeCount,!0;d=e}return!1},C.prototype.clear=function(){var a,b;if(!(this.size<=0)){for(a=0,b=this.buckets.length;b>a;++a)this.buckets[a]=-1;for(a=0;a=0;c=this.entries[c].next)if(this.entries[c].hashCode===b&&this.comparer(this.entries[c].key,a))return c;return-1},C.prototype.count=function(){return this.size-this.freeCount},C.prototype.tryGetValue=function(a){var b=this._findEntry(a);return b>=0?this.entries[b].value:d},C.prototype.getValues=function(){var a=0,b=[];if(this.entries)for(var c=0;c=0&&(b[a++]=this.entries[c].value);return b},C.prototype.get=function(a){var b=this._findEntry(a);if(b>=0)return this.entries[b].value;throw new Error(z)},C.prototype.set=function(a,b){this._insert(a,b,!1)},C.prototype.containskey=function(a){return this._findEntry(a)>=0},s.join=function(a,b,c,d){var e=this;return new u(function(f){var g=new n,h=!1,i=0,j=new C,k=!1,l=0,m=new C;return g.add(e.subscribe(function(a){var c,e,k,l,n=i++,o=new p;j.add(n,a),g.add(o),e=function(){return j.remove(n)&&0===j.count()&&h&&f.onCompleted(),g.remove(o)};try{c=b(a)}catch(q){return f.onError(q),void 0}o.setDisposable(c.take(1).subscribe(x,f.onError.bind(f),function(){e()})),l=m.getValues();for(var r=0;rm;m++)o[m].onError(t);return f.onError(t),void 0}for(f.onNext(s),q=k.getValues(),m=0,n=q.length;n>m;m++)c.onNext(q[m]);var u=new p;h.add(u);var w,x=function(){j.remove(e)&&c.onCompleted(),h.remove(u)};try{w=b(a)}catch(t){for(o=j.getValues(),m=0,n=j.length;n>m;m++)o[m].onError(t);return f.onError(t),void 0}u.setDisposable(w.take(1).subscribe(g,function(a){for(o=j.getValues(),m=0,n=o.length;n>m;m++)o[m].onError(a);f.onError(a)},x))},function(a){for(var b=j.getValues(),c=0,d=b.length;d>c;c++)b[c].onError(a);f.onError(a)},f.onCompleted.bind(f))),h.add(a.subscribe(function(a){var b,d,e,i=m++;k.add(i,a);var l=new p;h.add(l);var n,o=function(){k.remove(i),h.remove(l)};try{n=c(a)}catch(q){for(b=j.getValues(),d=0,e=j.length;e>d;d++)b[d].onError(q);return f.onError(q),void 0}for(l.setDisposable(n.take(1).subscribe(g,function(a){for(b=j.getValues(),d=0,e=j.length;e>d;d++)b[d].onError(a);f.onError(a)},o)),b=j.getValues(),d=0,e=b.length;e>d;d++)b[d].onNext(a)},function(a){for(var b=j.getValues(),c=0,d=b.length;d>c;c++)b[c].onError(a);f.onError(a)})),i})},s.buffer=function(){return this.window.apply(this,arguments).selectMany(function(a){return a.toArray()})},s.window=function(a,b){return 1===arguments.length&&"function"!=typeof arguments[0]?k.call(this,a):"function"==typeof a?l.call(this,a):j.call(this,a,b)},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.compat.js b/js/libs/rxjs/rx.compat.js new file mode 100644 index 0000000..451d3db --- /dev/null +++ b/js/libs/rxjs/rx.compat.js @@ -0,0 +1,4558 @@ +// 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 + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + 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.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + 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, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= 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) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + 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 () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (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; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, 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); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + 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); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!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); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + 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); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + 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; + } + }; + }; + + /** @private */ + 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; + }; + + /** @private */ + 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)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + 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) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + 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 (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @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)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + 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)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + 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; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + 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 (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + 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)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] 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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * 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. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * 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 AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @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) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * 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 AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * 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.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + 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. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + 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. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * 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. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * 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 (observer) { + return source.subscribe(observer); + }); + }; + + /** + * 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 (arguments.length === 1) { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * 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. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @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.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + */ + 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(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + 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. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @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 the accumulated values. + */ + 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 AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * 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 + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @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. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * 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 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. + * @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. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; 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 that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:eb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a,b){return new ec(function(c){var d=new tb,e=new ub;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return c.onError(g),void 0}E(f)&&(f=Vb(f)),d=new tb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function o(a,b){var c=this;return new ec(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return d.onError(i),void 0}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function p(a){return this.select(function(b,c){var d=a(b,c);return E(d)?Vb(d):d}).mergeObservable()}var q={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},r=q[typeof window]&&window||this,s=q[typeof exports]&&exports&&!exports.nodeType&&exports,t=q[typeof module]&&module&&!module.nodeType&&module,u=t&&t.exports===s&&s,v=q[typeof global]&&global;!v||v.global!==v&&v.window!==v||(r=v);var w={internals:{},config:{Promise:r.Promise},helpers:{}},x=w.helpers.noop=function(){},y=w.helpers.identity=function(a){return a},z=w.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}(),A=w.helpers.defaultComparer=function(a,b){return db(a,b)},B=w.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},C=w.helpers.defaultKeySerializer=function(a){return a.toString()},D=w.helpers.defaultError=function(a){throw a},E=w.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then&&a.then!==w.Observable.prototype.then},F=(w.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},w.helpers.not=function(a){return!a},"Sequence contains no elements."),G="Argument out of range",H="Object has been disposed",I="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";r.Set&&"function"==typeof(new r.Set)["@@iterator"]&&(I="@@iterator");var J,K={done:!0,value:a},L="[object Arguments]",M="[object Array]",N="[object Boolean]",O="[object Date]",P="[object Error]",Q="[object Function]",R="[object Number]",S="[object Object]",T="[object RegExp]",U="[object String]",V=Object.prototype.toString,W=Object.prototype.hasOwnProperty,X=V.call(arguments)==L,Y=Error.prototype,Z=Object.prototype,$=Z.propertyIsEnumerable;try{J=!(V.call(document)==S&&!({toString:0}+""))}catch(_){J=!0}var ab=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bb={};bb[M]=bb[O]=bb[R]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},bb[N]=bb[U]={constructor:!0,toString:!0,valueOf:!0},bb[P]=bb[Q]=bb[T]={constructor:!0,toString:!0},bb[S]={constructor:!0};var cb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);cb.enumErrorProps=$.call(Y,"message")||$.call(Y,"name"),cb.enumPrototypes=$.call(a,"prototype"),cb.nonEnumArgs=0!=c,cb.nonEnumShadows=!/valueOf/.test(b)}(1),X||(h=function(a){return a&&"object"==typeof a?W.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&V.call(a)==Q});var db=w.internals.isEqual=function(a,b){return j(a,b,[],[])},eb=Array.prototype.slice,fb=({}.hasOwnProperty,this.inherits=w.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),gb=w.internals.addProperties=function(a){for(var b=eb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},hb=w.internals.addRef=function(a,b){return new ec(function(c){return new nb(b.getDisposable(),a.subscribe(c))})};Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=eb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(eb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(eb.call(arguments)))};return d});var ib=Object("a"),jb="a"!=ib[0]||!(0 in ib);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=jb&&{}.toString.call(this)==U?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=Q)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=jb&&{}.toString.call(this)==U?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=Q)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return Object.prototype.toString.call(a)==M}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var kb=function(a,b){this.id=a,this.value=b};kb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var lb=w.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},mb=lb.prototype;mb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},mb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},mb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},ob.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},ob.contains=function(a){return-1!==this.disposables.indexOf(a)},ob.toArray=function(){return this.disposables.slice(0)};var pb=w.Disposable=function(a){this.isDisposed=!1,this.action=a||x};pb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var qb=pb.create=function(a){return new pb(a)},rb=pb.empty={dispose:x},sb=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),tb=w.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return fb(b,a),b}(sb),ub=w.SerialDisposable=function(a){function b(){a.call(this,!1)}return fb(b,a),b}(sb),vb=w.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?rb:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var wb=w.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||B,this.disposable=new tb};wb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},wb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},wb.prototype.isCancelled=function(){return this.disposable.isDisposed},wb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var xb,yb=w.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new nb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),rb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new nb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),rb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),rb}var e=a.prototype;return e.catchException=e["catch"]=function(a){return new Db(this,a)},e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return qb(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=z,a.normalize=function(a){return 0>a&&(a=0),a},a}(),zb=yb.normalize,Ab=(w.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new tb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),yb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=zb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new yb(z,a,b,c)}()),Bb=yb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-yb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+yb.normalize(c),g=new wb(this,b,d,f);if(e)e.enqueue(g);else{e=new lb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new yb(z,b,c,d);return f.scheduleRequired=function(){return null===e},f.ensureTrampoline=function(a){return null===e?this.schedule(a):a()},f}(),Cb=x;!function(){function a(){if(!r.postMessage||r.importScripts)return!1;var a=!1,b=r.onmessage;return r.onmessage=function(){a=!0},r.postMessage("","*"),r.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(V).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=v&&u&&v.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=v&&u&&v.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))xb=process.nextTick;else if("function"==typeof d)xb=d,Cb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;r.addEventListener?r.addEventListener("message",b,!1):r.attachEvent("onmessage",b,!1),xb=function(a){var b=h++;g[b]=a,r.postMessage(f+b,"*")}}else if(r.MessageChannel){var i=new r.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},xb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in r&&"onreadystatechange"in r.document.createElement("script")?xb=function(a){var b=r.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},r.document.documentElement.appendChild(b)}:(xb=function(a){return setTimeout(a,0)},Cb=clearTimeout)}();var Db=(yb.timeout=function(){function a(a,b){var c=this,d=new tb,e=xb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new nb(d,qb(function(){Cb(e)}))}function b(a,b,c){var d=this,e=yb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new tb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new nb(f,qb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new yb(z,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return fb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return rb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new tb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(yb)),Eb=w.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}var b=a.prototype;return b.accept=function(a,b,c){return 1===arguments.length&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},b.toObservable=function(a){var b=this;return a||(a=Ab),new ec(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Fb=Eb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Eb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Gb=Eb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Eb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Hb=Eb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Eb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Ib=w.internals.Enumerator=function(a){this._next=a};Ib.prototype.next=function(){return this._next()},Ib.prototype[I]=function(){return this};var Jb=w.internals.Enumerable=function(a){this._iterator=a};Jb.prototype[I]=function(){return this._iterator()},Jb.prototype.concat=function(){var a=this;return new ec(function(b){var c;try{c=a[I]()}catch(d){return b.onError(),void 0}var e,f=new ub,g=Ab.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return b.onError(g),void 0}if(d.done)return b.onCompleted(),void 0;var h=d.value;E(h)&&(h=Vb(h));var i=new tb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new nb(f,g,qb(function(){e=!0}))})},Jb.prototype.catchException=function(){var a=this;return new ec(function(b){var c;try{c=a[I]()}catch(d){return b.onError(),void 0}var e,f,g=new ub,h=Ab.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return b.onError(h),void 0}if(d.done)return f?b.onError(f):b.onCompleted(),void 0;var i=d.value;E(i)&&(i=Vb(i));var j=new tb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new nb(g,h,qb(function(){e=!0}))})};var Kb=Jb.repeat=function(a,b){return null==b&&(b=-1),new Jb(function(){var c=b;return new Ib(function(){return 0===c?K:(c>0&&c--,{done:!1,value:a})})})},Lb=Jb.forEach=function(a,b,c){return b||(b=y),new Jb(function(){var d=-1;return new Ib(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return b.isAcquired=!1,void 0;c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Pb),Tb=function(a){function b(){a.apply(this,arguments)}return fb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Sb),Ub=w.Observable=function(){function a(a){this._subscribe=a}return Ob=a.prototype,Ob.finalValue=function(){var a=this;return new ec(function(b){var c,d=!1;return a.subscribe(function(a){d=!0,c=a},b.onError.bind(b),function(){d?(b.onNext(c),b.onCompleted()):b.onError(new Error(F))})})},Ob.subscribe=Ob.forEach=function(a,b,c){var d;return d="object"==typeof a?a:Nb(a,b,c),this._subscribe(d)},Ob.toArray=function(){function a(a,b){var c=a.slice(0);return c.push(b),c}return this.scan([],a).startWith([]).finalValue()},a}();Ob.observeOn=function(a){var b=this;return new ec(function(c){return b.subscribe(new Tb(a,c))})},Ob.subscribeOn=function(a){var b=this;return new ec(function(c){var d=new tb,e=new ub;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var Vb=Ub.fromPromise=function(a){return new ec(function(b){return a.then(function(a){b.onNext(a),b.onCompleted()},function(a){b.onError(a)}),function(){a&&a.abort&&a.abort()}})};Ob.toPromise=function(a){if(a||(a=w.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Ub.create=Ub.createWithDisposable=function(a){return new ec(a)};var Wb=(Ub.defer=function(a){return new ec(function(b){var c;try{c=a()}catch(d){return $b(d).subscribe(b)}return E(c)&&(c=Vb(c)),c.subscribe(b)})},Ub.empty=function(a){return a||(a=Ab),new ec(function(b){return a.schedule(function(){b.onCompleted()})})}),Xb=Ub.fromArray=function(a,b){return b||(b=Bb),new ec(function(c){var d=0;return b.scheduleRecursive(function(b){dc?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Ub.repeat=function(a,b,c){return c||(c=Bb),null==b&&(b=-1),Zb(a,c).repeat(b)};var Zb=Ub["return"]=Ub.returnValue=function(a,b){return b||(b=Ab),new ec(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},$b=Ub["throw"]=Ub.throwException=function(a,b){return b||(b=Ab),new ec(function(c){return b.schedule(function(){c.onError(a)})})};Ub.using=function(a,b){return new ec(function(c){var d,e,f=rb;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new nb($b(g).subscribe(c),f)}return new nb(e.subscribe(c),f)})},Ob.amb=function(a){var b=this;return new ec(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new tb,j=new tb;return E(a)&&(a=Vb(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new nb(i,j)})},Ub.amb=function(){function a(a,b){return a.amb(b)}for(var b=Yb(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},Ob["catch"]=Ob.catchException=function(a){return"function"==typeof a?n(this,a):_b([this,a])};var _b=Ub.catchException=Ub["catch"]=function(){var a=k(arguments,0);return Lb(a).catchException()};Ob.combineLatest=function(){var a=eb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),ac.apply(this,a)};var ac=Ub.combineLatest=function(){var a=eb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new ec(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(y))){try{d=b.apply(null,k)}catch(e){return c.onError(e),void 0}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(y)&&c.onCompleted()}function e(a){j[a]=!0,j.every(y)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new tb;E(f)&&(f=Vb(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new nb(m)})};Ob.concat=function(){var a=eb.call(arguments,0);return a.unshift(this),bc.apply(this,a)};var bc=Ub.concat=function(){var a=k(arguments,0);return Lb(a).concat()};Ob.concatObservable=Ob.concatAll=function(){return this.merge(1)},Ob.merge=function(a){if("number"!=typeof a)return cc(this,a);var b=this;return new ec(function(c){var d=0,e=new nb,f=!1,g=[],h=function(a){var b=new tb;e.add(b),E(a)&&(a=Vb(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){var a;e.remove(b),g.length>0?(a=g.shift(),h(a)):(d--,f&&0===d&&c.onCompleted())}))};return e.add(b.subscribe(function(b){a>d?(d++,h(b)):g.push(b)},c.onError.bind(c),function(){f=!0,0===d&&c.onCompleted()})),e})};var cc=Ub.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=eb.call(arguments,1)):(a=Ab,b=eb.call(arguments,0)):(a=Ab,b=eb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Xb(b,a).mergeObservable()};Ob.mergeObservable=Ob.mergeAll=function(){var a=this;return new ec(function(b){var c=new nb,d=!1,e=new tb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new tb;c.add(e),E(a)&&(a=Vb(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Ob.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return dc([this,a])};var dc=Ub.onErrorResumeNext=function(){var a=k(arguments,0);return new ec(function(b){var c=0,d=new ub,e=Ab.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return d.onError(g),void 0}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(y)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new tb;E(c)&&(c=Vb(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k); +return new nb(j)})},Ub.zip=function(){var a=eb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Ub.zipArray=function(){var a=k(arguments,0);return new ec(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(y))return b.onCompleted(),void 0}function d(a){return g[a]=!0,g.every(y)?(b.onCompleted(),void 0):void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new tb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new nb(h);return j.add(qb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Ob.asObservable=function(){var a=this;return new ec(function(b){return a.subscribe(b)})},Ob.bufferWithCount=function(a,b){return 1===arguments.length&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},Ob.dematerialize=function(){var a=this;return new ec(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Ob.distinctUntilChanged=function(a,b){var c=this;return a||(a=y),b||(b=A),new ec(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return d.onError(i),void 0}if(f)try{h=b(e,g)}catch(i){return d.onError(i),void 0}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Ob["do"]=Ob.doAction=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new ec(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Ob["finally"]=Ob.finallyAction=function(a){var b=this;return new ec(function(c){var d=b.subscribe(c);return qb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Ob.ignoreElements=function(){var a=this;return new ec(function(b){return a.subscribe(x,b.onError.bind(b),b.onCompleted.bind(b))})},Ob.materialize=function(){var a=this;return new ec(function(b){return a.subscribe(function(a){b.onNext(Fb(a))},function(a){b.onNext(Gb(a)),b.onCompleted()},function(){b.onNext(Hb()),b.onCompleted()})})},Ob.repeat=function(a){return Kb(this,a).concat()},Ob.retry=function(a){return Kb(this,a).catchException()},Ob.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new ec(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return e.onError(i),void 0}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Ob.skipLast=function(a){var b=this;return new ec(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Ob.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Ab,a=eb.call(arguments,c),Lb([Xb(a,b),this]).concat()},Ob.takeLast=function(a,b){return this.takeLastBuffer(a).selectMany(function(a){return Xb(a,b)})},Ob.takeLastBuffer=function(a){var b=this;return new ec(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Ob.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(G);if(1===arguments.length&&(b=a),0>=b)throw new Error(G);return new ec(function(d){var e=new tb,f=new vb(e),g=0,h=[],i=function(){var a=new ic;h.push(a),d.onNext(hb(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},Ob.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new ec(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},Ob.distinct=function(a,b){var c=this;return a||(a=y),b||(b=C),new ec(function(d){var e={};return c.subscribe(function(c){var f,g,h,i=!1;try{f=a(c),g=b(f)}catch(j){return d.onError(j),void 0}for(h in e)if(g===h){i=!0;break}i||(e[g]=null,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.groupBy=function(a,b,c){return this.groupByUntil(a,b,function(){return Yb()},c)},Ob.groupByUntil=function(a,b,c,d){var e=this;return b||(b=y),d||(d=C),new ec(function(f){var g={},h=new nb,i=new vb(h);return h.add(e.subscribe(function(e){var j,k,l,m,n,o,p,q,r,s;try{o=a(e),p=d(o)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}m=!1;try{r=g[p],r||(r=new ic,g[p]=r,m=!0)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}if(m){n=new gc(o,r,i),k=new gc(o,r);try{j=c(k)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}f.onNext(n),q=new tb,h.add(q);var u=function(){p in g&&(delete g[p],r.onCompleted()),h.remove(q)};q.setDisposable(j.take(1).subscribe(x,function(a){for(s in g)g[s].onError(a);f.onError(a)},function(){u()}))}try{l=b(e)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}r.onNext(l)},function(a){for(var b in g)g[b].onError(a);f.onError(a)},function(){for(var a in g)g[a].onCompleted();f.onCompleted()})),i})},Ob.select=Ob.map=function(a,b){var c=this;return new ec(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.pluck=function(a){return this.select(function(b){return b[a]})},Ob.selectMany=Ob.flatMap=function(a,b){return b?this.selectMany(function(c,d){var e=a(c,d),f=E(e)?Vb(e):e;return f.select(function(a){return b(c,a,d)})}):"function"==typeof a?p.call(this,a):p.call(this,function(){return a})},Ob.selectSwitch=Ob.flatMapLatest=function(a,b){return this.select(a,b).switchLatest()},Ob.skip=function(a){if(0>a)throw new Error(G);var b=this;return new ec(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Ob.skipWhile=function(a,b){var c=this;return new ec(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.take=function(a,b){if(0>a)throw new Error(G);if(0===a)return Wb(b);var c=this;return new ec(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Ob.takeWhile=function(a,b){var c=this;return new ec(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.where=Ob.filter=function(a,b){var c=this;return new ec(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})};var ec=w.AnonymousObservable=function(a){function b(a){return"undefined"==typeof a?a=rb:"function"==typeof a&&(a=qb(a)),a}function c(d){function e(a){var c=new fc(a);if(Bb.scheduleRequired())Bb.schedule(function(){try{c.setDisposable(b(d(c)))}catch(a){if(!c.fail(a))throw a}});else try{c.setDisposable(b(d(c)))}catch(e){if(!c.fail(e))throw e}return c}return this instanceof c?(a.call(this,e),void 0):new c(d)}return fb(c,a),c}(Ub),fc=function(a){function b(b){a.call(this),this.observer=b,this.m=new tb}fb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Pb),gc=function(a){function b(a){return this.underlyingObservable.subscribe(a)}function c(c,d,e){a.call(this,b),this.key=c,this.underlyingObservable=e?new ec(function(a){return new nb(e.getDisposable(),d.subscribe(a))}):d}return fb(c,a),c}(Ub),hc=function(a,b){this.subject=a,this.observer=b};hc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var ic=w.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),rb):(a.onCompleted(),rb):(this.observers.push(a),new hc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return fb(d,a),gb(d.prototype,Mb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new jc(a,b)},d}(Ub),jc=(w.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new hc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),rb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return fb(d,a),gb(d.prototype,Mb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Ub),function(a){function b(a){return this.observable.subscribe(a)}function c(c,d){a.call(this,b),this.observer=c,this.observable=d}return fb(c,a),gb(c.prototype,Mb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),c}(Ub));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(r.Rx=w,define(function(){return w})):s&&t?u?(t.exports=w).Rx=w:s.Rx=w:r.Rx=w}).call(this); \ No newline at end of file diff --git a/js/libs/rxjs/rx.experimental.js b/js/libs/rxjs/rx.experimental.js new file mode 100644 index 0000000..f7d5ef0 --- /dev/null +++ b/js/libs/rxjs/rx.experimental.js @@ -0,0 +1,471 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableConcat = Observable.concat, + observableDefer = Observable.defer, + observableEmpty = Observable.empty, + disposableEmpty = Rx.Disposable.empty, + CompositeDisposable = Rx.CompositeDisposable, + SerialDisposable = Rx.SerialDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + Enumerator = Rx.internals.Enumerator, + Enumerable = Rx.internals.Enumerable, + enumerableForEach = Enumerable.forEach, + immediateScheduler = Rx.Scheduler.immediate, + currentThreadScheduler = Rx.Scheduler.currentThread, + slice = Array.prototype.slice, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + noop = Rx.helpers.noop, + isPromise = Rx.helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * 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. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + 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 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; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + scheduler || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .select( + function (x) { + var curr = new ChainObservable(x); + if (chain) { + chain.onNext(x); + } + chain = curr; + + return curr; + }) + .doAction( + noop, + function (e) { + if (chain) { + chain.onError(e); + } + }, + function () { + if (chain) { + chain.onCompleted(); + } + }) + .observeOn(scheduler) + .select(function (x, i, o) { return selector(x, i, o); }); + }); + }; + + var ChainObservable = (function (_super) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, _super); + + function ChainObservable(head) { + _super.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.experimental.min.js b/js/libs/rxjs/rx.experimental.min.js new file mode 100644 index 0000000..5ac325b --- /dev/null +++ b/js/libs/rxjs/rx.experimental.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:v.call(a)}function f(a,b){return new r(function(){return new q(function(){return a()?{done:!1,value:b}:{done:!0,value:d}})})}var g=c.Observable,h=g.prototype,i=c.AnonymousObservable,j=g.concat,k=g.defer,l=g.empty,m=c.Disposable.empty,n=c.CompositeDisposable,o=c.SerialDisposable,p=c.SingleAssignmentDisposable,q=c.internals.Enumerator,r=c.internals.Enumerable,s=r.forEach,t=c.Scheduler.immediate,u=c.Scheduler.currentThread,v=Array.prototype.slice,w=c.AsyncSubject,x=c.Observer,y=c.internals.inherits,z=c.internals.addProperties,A=c.helpers.noop,B=c.helpers.isPromise,C=g.fromPromise,D="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";a.Set&&"function"==typeof(new a.Set)["@@iterator"]&&(D="@@iterator");h.letBind=h.let=function(a){return a(this)},g["if"]=g.ifThen=function(a,b,c){return k(function(){return c||(c=l()),B(b)&&(b=C(b)),B(c)&&(c=C(c)),"function"==typeof c.now&&(c=l(c)),a()?b:c})},g["for"]=g.forIn=function(a,b){return s(a,b).concat()};var E=g["while"]=g.whileDo=function(a,b){return B(b)&&(b=C(b)),f(a,b).concat()};h.doWhile=function(a){return j([this,E(a,this)])},g["case"]=g.switchCase=function(a,b,c){return k(function(){c||(c=l()),"function"==typeof c.now&&(c=l(c));var d=b[a()];return B(d)&&(d=C(d)),d||c})},h.expand=function(a,b){b||(b=t);var c=this;return new i(function(d){var e=[],f=new o,g=new n(f),h=0,i=!1,j=function(){var c=!1;e.length>0&&(c=!i,i=!0),c&&f.setDisposable(b.scheduleRecursive(function(b){var c;if(!(e.length>0))return i=!1,void 0;c=e.shift();var f=new p;g.add(f),f.setDisposable(c.subscribe(function(b){d.onNext(b);var c=null;try{c=a(b)}catch(f){d.onError(f)}e.push(c),h++,j()},d.onError.bind(d),function(){g.remove(f),h--,0===h&&d.onCompleted()})),b()}))};return e.push(c),h++,j(),g})},g.forkJoin=function(){var a=e(arguments,0);return new i(function(b){var c=a.length;if(0===c)return b.onCompleted(),m;for(var d=new n,e=!1,f=new Array(c),g=new Array(c),h=new Array(c),i=0;c>i;i++)!function(i){var j=a[i];B(j)&&(j=C(j)),d.add(j.subscribe(function(a){e||(f[i]=!0,h[i]=a)},function(a){e=!0,b.onError(a),d.dispose()},function(){if(!e){if(!f[i])return b.onCompleted(),void 0;g[i]=!0;for(var a=0;c>a;a++)if(!g[a])return;e=!0,b.onNext(h),b.onCompleted()}}))}(i);return d})},h.forkJoin=function(a,b){var c=this;return new i(function(d){var e,f,g=!1,h=!1,i=!1,j=!1,k=new p,l=new p;return B(a)&&(a=C(a)),k.setDisposable(c.subscribe(function(a){i=!0,e=a},function(a){l.dispose(),d.onError(a)},function(){if(g=!0,h)if(i)if(j){var a;try{a=b(e,f)}catch(c){return d.onError(c),void 0}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),l.setDisposable(a.subscribe(function(a){j=!0,f=a},function(a){k.dispose(),d.onError(a)},function(){if(h=!0,g)if(i)if(j){var a;try{a=b(e,f)}catch(c){return d.onError(c),void 0}d.onNext(a),d.onCompleted()}else d.onCompleted();else d.onCompleted()})),new n(k,l)})},h.manySelect=function(a,b){b||(b=t);var c=this;return k(function(){var d;return c.select(function(a){var b=new F(a);return d&&d.onNext(a),d=b,b}).doAction(A,function(a){d&&d.onError(a)},function(){d&&d.onCompleted()}).observeOn(b).select(function(b,c,d){return a(b,c,d)})})};var F=function(a){function b(a){var b=this,c=new n;return c.add(u.schedule(function(){a.onNext(b.head),c.add(b.tail.mergeObservable().subscribe(a))})),c}function c(c){a.call(this,b),this.head=c,this.tail=new w}return y(c,a),z(c.prototype,x,{onCompleted:function(){this.onNext(g.empty())},onError:function(a){this.onNext(g.throwException(a))},onNext:function(a){this.tail.onNext(a),this.tail.onCompleted()}}),c}(g);return c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.joinpatterns.js b/js/libs/rxjs/rx.joinpatterns.js new file mode 100644 index 0000000..481f694 --- /dev/null +++ b/js/libs/rxjs/rx.joinpatterns.js @@ -0,0 +1,415 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableThrow = Observable.throwException, + observerCreate = Rx.Observer.create, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + CompositeDisposable = Rx.CompositeDisposable, + AbstractObserver = Rx.internals.AbstractObserver, + noop = Rx.helpers.noop, + defaultComparer = Rx.internals.isEqual, + inherits = Rx.internals.inherits, + slice = Array.prototype.slice; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.then = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.then = function (selector) { + return new Pattern([this]).then(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.joinpatterns.min.js b/js/libs/rxjs/rx.joinpatterns.min.js new file mode 100644 index 0000000..f6c42e8 --- /dev/null +++ b/js/libs/rxjs/rx.joinpatterns.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:s.call(a)}function e(a){this.patterns=a}function f(a,b){this.expression=a,this.selector=b}function g(a,b,c){var d=a.get(b);if(!d){var e=new u(b,c);return a.set(b,e),e}return d}function h(a,b,c){var d,e;for(this.joinObserverArray=a,this.onNext=b,this.onCompleted=c,this.joinObservers=new t,d=0;df;f++)e.push(g(a,this.expression.patterns[f],b.onError.bind(b)));var j=new h(e,function(){var a;try{a=d.selector.apply(d,arguments)}catch(c){return b.onError(c),void 0}b.onNext(a)},function(){for(var a=0,b=e.length;b>a;a++)e[a].removeActivePlan(j);c(j)});for(f=0,i=e.length;i>f;f++)e[f].addActivePlan(j);return j},h.prototype.dequeue=function(){for(var a=this.joinObservers.getValues(),b=0,c=a.length;c>b;b++)a[b].queue.shift()},h.prototype.match=function(){var a,b,c,d,e,f=!0;for(b=0,c=this.joinObserverArray.length;c>b;b++)if(0===this.joinObserverArray[b].queue.length){f=!1;break}if(f){for(a=[],d=!1,b=0,c=this.joinObserverArray.length;c>b;b++)a.push(this.joinObserverArray[b].queue[0]),"C"===this.joinObserverArray[b].queue[0].kind&&(d=!0);if(d)this.onCompleted();else{for(this.dequeue(),e=[],b=0;bc;c++)b[c].match()}},c.error=q,c.completed=q,c.addActivePlan=function(a){this.activePlans.push(a)},c.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},c.removeActivePlan=function(a){var b=this.activePlans.indexOf(a);this.activePlans.splice(b,1),0===this.activePlans.length&&this.dispose()},c.dispose=function(){a.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},b}(p);return j.and=function(a){return new e([this,a])},j.then=function(a){return new e([this]).then(a)},i.when=function(){var a=d(arguments,0);return new k(function(b){var c,d,e,f,g,h,i=[],j=new t;h=m(b.onNext.bind(b),function(a){for(var c=j.getValues(),d=0,e=c.length;e>d;d++)c[d].onError(a);b.onError(a)},b.onCompleted.bind(b));try{for(d=0,e=a.length;e>d;d++)i.push(a[d].activate(j,h,function(a){var b=i.indexOf(a);i.splice(b,1),0===i.length&&h.onCompleted()}))}catch(k){l(k).subscribe(b)}for(c=new o,g=j.getValues(),d=0,e=g.length;e>d;d++)f=g[d],f.subscribe(),c.add(f);return c})},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.js b/js/libs/rxjs/rx.js new file mode 100644 index 0000000..09dffa8 --- /dev/null +++ b/js/libs/rxjs/rx.js @@ -0,0 +1,4440 @@ +// 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 + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + 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.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + 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, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= 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) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + 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 () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (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; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, 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); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + 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); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!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); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + 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); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + 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; + } + }; + }; + + /** @private */ + 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; + }; + + /** @private */ + 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)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + 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) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + 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 (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @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)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + 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)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + 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; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + 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 (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + 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)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] 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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * 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. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * 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 AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @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) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * 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 AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * 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.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + 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. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + 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. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * 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. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * 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 (observer) { + return source.subscribe(observer); + }); + }; + + /** + * 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 (arguments.length === 1) { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * 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. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @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.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + */ + 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(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + 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. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @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 the accumulated values. + */ + 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 AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * 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 + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 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} [keySerializer] Used to serialize the given object into a string for object comparison. + * @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, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @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. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * 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 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. + * @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. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; 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 that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= 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) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + 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 () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (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; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, 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); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!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); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + 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) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + 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 (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @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)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + 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)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] 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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + 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 (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + 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)); + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @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) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * 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 AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * 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.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * 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. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * 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 (observer) { + return source.subscribe(observer); + }); + }; + + /** + * 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. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @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.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + */ + 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(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + 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. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @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 the accumulated values. + */ + 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 AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @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. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * 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 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. + * @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. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; 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 that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 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); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + var schedulerMethod, source = this; + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + if (dueTime instanceof Date) { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithAbsolute(dt, action); + }; + } else { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithRelative(dt, action); + }; + } + return new AnonymousObservable(function (observer) { + var createTimer, + id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + subscription.setDisposable(original); + createTimer = function () { + var myId = id; + timer.setDisposable(schedulerMethod(dueTime, function () { + switched = id === myId; + var timerWins = switched; + if (timerWins) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + createTimer(); + original.setDisposable(source.subscribe(function (x) { + var onNextWins = !switched; + if (onNextWins) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + var onErrorWins = !switched; + if (onErrorWins) { + id++; + observer.onError(e); + } + }, function () { + var onCompletedWins = !switched; + if (onCompletedWins) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + 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) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + 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(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer) + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * 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 {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (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.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + var AnonymousObservable = Rx.AnonymousObservable = (function (_super) { + inherits(AnonymousObservable, _super); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }); + } else { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + } + + return autoDetachObserver; + } + + _super.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + 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 noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + 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; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + 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. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _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(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/js/libs/rxjs/rx.lite.compat.min.js b/js/libs/rxjs/rx.lite.compat.min.js new file mode 100644 index 0000000..fae920a --- /dev/null +++ b/js/libs/rxjs/rx.lite.compat.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(M)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;hb.nonEnumArgs&&a.length&&h(a)&&(a=jb.call(a));var d=hb.enumPrototypes&&"function"==typeof a,e=hb.enumErrorProps&&(a===bb||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(hb.nonEnumShadows&&a!==cb){var g=a.constructor,i=-1,j=fb.length;if(a===(g&&g.prototype))var k=a===stringProto?Z:a===bb?U:$.call(a),l=gb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:jb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){return new pc(function(c){var d=new xb,e=new yb;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return c.onError(g),void 0}J(f)&&(f=hc(f)),d=new xb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function n(a,b){var c=this;return new pc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return d.onError(i),void 0}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function o(a){return this.select(function(b,c){var d=a(b,c);return J(d)?hc(d):d}).mergeObservable()}function p(a){var b=function(){this.cancelBubble=!0},c=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(a){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(a||(a=x.event),!a.target)switch(a.target=a.target||a.srcElement,"mouseover"==a.type&&(a.relatedTarget=a.fromElement),"mouseout"==a.type&&(a.relatedTarget=a.toElement),a.stopPropagation||(a.stopPropagation=b,a.preventDefault=c),a.type){case"keypress":var d="charCode"in a?a.charCode:a.keyCode;10==d?(d=0,a.keyCode=13):13==d||27==d?d=0:3==d&&(d=99),a.charCode=d,a.keyChar=a.charCode?String.fromCharCode(a.charCode):""}return a}function q(a,b,c){if(a.addListener)return a.addListener(b,c),ub(function(){a.removeListener(b,c)});if(a.addEventListener)return a.addEventListener(b,c,!1),ub(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var d=function(a){c(p(a))};return a.attachEvent("on"+b,d),ub(function(){a.detachEvent("on"+b,d)})}return a["on"+b]=c,ub(function(){a["on"+b]=null})}function r(a,b,c){var d=new rb;if("function"==typeof a.item&&"number"==typeof a.length)for(var e=0,f=a.length;f>e;e++)d.add(r(a.item(e),b,c));else a&&d.add(q(a,b,c));return d}function s(a,b){var c=Cb(a);return new pc(function(a){return b.scheduleWithRelative(c,function(){a.onNext(0),a.onCompleted()})})}function t(a,b,c){return a===b?new pc(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):Wb(function(){return observableTimerDateAndPeriod(c.now()+a,b,c)})}function u(a,b){return new pc(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new rb(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}function v(a,b,c){return new pc(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(E))){try{e=c.apply(null,j)}catch(f){return d.onError(f),void 0}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new rb(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var w={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},x=w[typeof window]&&window||this,y=w[typeof exports]&&exports&&!exports.nodeType&&exports,z=w[typeof module]&&module&&!module.nodeType&&module,A=z&&z.exports===y&&y,B=w[typeof global]&&global;!B||B.global!==B&&B.window!==B||(x=B);var C={internals:{},config:{Promise:x.Promise},helpers:{}},D=C.helpers.noop=function(){},E=C.helpers.identity=function(a){return a},F=C.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}(),G=C.helpers.defaultComparer=function(a,b){return ib(a,b)},H=C.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},I=(C.helpers.defaultKeySerializer=function(a){return a.toString()},C.helpers.defaultError=function(a){throw a}),J=C.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then&&a.then!==C.Observable.prototype.then},K=(C.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},C.helpers.not=function(a){return!a},"Sequence contains no elements."),L="Argument out of range",M="Object has been disposed",N="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";x.Set&&"function"==typeof(new x.Set)["@@iterator"]&&(N="@@iterator");var O,P={done:!0,value:a},Q="[object Arguments]",R="[object Array]",S="[object Boolean]",T="[object Date]",U="[object Error]",V="[object Function]",W="[object Number]",X="[object Object]",Y="[object RegExp]",Z="[object String]",$=Object.prototype.toString,_=Object.prototype.hasOwnProperty,ab=$.call(arguments)==Q,bb=Error.prototype,cb=Object.prototype,db=cb.propertyIsEnumerable;try{O=!($.call(document)==X&&!({toString:0}+""))}catch(eb){O=!0}var fb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],gb={};gb[R]=gb[T]=gb[W]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},gb[S]=gb[Z]={constructor:!0,toString:!0,valueOf:!0},gb[U]=gb[V]=gb[Y]={constructor:!0,toString:!0},gb[X]={constructor:!0};var hb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);hb.enumErrorProps=db.call(bb,"message")||db.call(bb,"name"),hb.enumPrototypes=db.call(a,"prototype"),hb.nonEnumArgs=0!=c,hb.nonEnumShadows=!/valueOf/.test(b)}(1),ab||(h=function(a){return a&&"object"==typeof a?_.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&$.call(a)==V});{var ib=C.internals.isEqual=function(a,b){return j(a,b,[],[])},jb=Array.prototype.slice,kb=({}.hasOwnProperty,this.inherits=C.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),lb=C.internals.addProperties=function(a){for(var b=jb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}};C.internals.addRef=function(a,b){return new pc(function(c){return new rb(b.getDisposable(),a.subscribe(c))})}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=jb.call(arguments,1),d=function(){function e(){}if(this instanceof d){e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(jb.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(jb.call(arguments)))};return d});var mb=Object("a"),nb="a"!=mb[0]||!(0 in mb);Array.prototype.every||(Array.prototype.every=function(a){var b=Object(this),c=nb&&{}.toString.call(this)==Z?this.split(""):b,d=c.length>>>0,e=arguments[1];if({}.toString.call(a)!=V)throw new TypeError(a+" is not a function");for(var f=0;d>f;f++)if(f in c&&!a.call(e,c[f],f,b))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(a){var b=Object(this),c=nb&&{}.toString.call(this)==Z?this.split(""):b,d=c.length>>>0,e=Array(d),f=arguments[1];if({}.toString.call(a)!=V)throw new TypeError(a+" is not a function");for(var g=0;d>g;g++)g in c&&(e[g]=a.call(f,c[g],g,b));return e}),Array.prototype.filter||(Array.prototype.filter=function(a){for(var b,c=[],d=new Object(this),e=0,f=d.length>>>0;f>e;e++)b=d[e],e in d&&a.call(arguments[1],b,e,d)&&c.push(b);return c}),Array.isArray||(Array.isArray=function(a){return Object.prototype.toString.call(a)==R}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=Object(this),c=b.length>>>0;if(0===c)return-1;var d=0;if(arguments.length>1&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!=d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1});var ob=function(a,b){this.id=a,this.value=b};ob.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var pb=C.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},qb=pb.prototype;qb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},qb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},qb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},sb.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},sb.contains=function(a){return-1!==this.disposables.indexOf(a)},sb.toArray=function(){return this.disposables.slice(0)};var tb=C.Disposable=function(a){this.isDisposed=!1,this.action=a||D};tb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ub=tb.create=function(a){return new tb(a)},vb=tb.empty={dispose:D},wb=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),xb=C.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return kb(b,a),b}(wb),yb=C.SerialDisposable=function(a){function b(){a.call(this,!1)}return kb(b,a),b}(wb),zb=(C.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?vb:new a(this)},b}(),C.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||H,this.disposable=new xb});zb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},zb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},zb.prototype.isCancelled=function(){return this.disposable.isDisposed},zb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ab,Bb=C.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new rb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),vb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new rb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),vb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),vb}var e=a.prototype;return e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return ub(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=F,a.normalize=function(a){return 0>a&&(a=0),a},a}(),Cb=Bb.normalize,Db=Bb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=Cb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Bb(F,a,b,c)}(),Eb=Bb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-Bb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+Bb.normalize(c),g=new zb(this,b,d,f);if(e)e.enqueue(g);else{e=new pb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new Bb(F,b,c,d);return f.scheduleRequired=function(){return null===e},f.ensureTrampoline=function(a){return null===e?this.schedule(a):a()},f}(),Fb=(C.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new xb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),D);!function(){function a(){if(!x.postMessage||x.importScripts)return!1;var a=!1,b=x.onmessage;return x.onmessage=function(){a=!0},x.postMessage("","*"),x.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String($).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=B&&A&&B.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=B&&A&&B.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Ab=process.nextTick;else if("function"==typeof d)Ab=d,Fb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;x.addEventListener?x.addEventListener("message",b,!1):x.attachEvent("onmessage",b,!1),Ab=function(a){var b=h++;g[b]=a,x.postMessage(f+b,"*")}}else if(x.MessageChannel){var i=new x.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},Ab=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in x&&"onreadystatechange"in x.document.createElement("script")?Ab=function(a){var b=x.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},x.document.documentElement.appendChild(b)}:(Ab=function(a){return setTimeout(a,0)},Fb=clearTimeout)}();var Gb=Bb.timeout=function(){function a(a,b){var c=this,d=new xb,e=Ab(function(){d.isDisposed||d.setDisposable(b(c,a))});return new rb(d,ub(function(){Fb(e)}))}function b(a,b,c){var d=this,e=Bb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new xb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new rb(f,ub(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new Bb(F,a,b,c)}(),Hb=C.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}var b=a.prototype;return b.accept=function(a,b,c){return 1===arguments.length&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},b.toObservable=function(a){var b=this;return a||(a=Db),new pc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Ib=Hb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Hb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Jb=Hb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Hb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Kb=Hb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Hb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Lb=C.internals.Enumerator=function(a){this._next=a};Lb.prototype.next=function(){return this._next()},Lb.prototype[N]=function(){return this};var Mb=C.internals.Enumerable=function(a){this._iterator=a};Mb.prototype[N]=function(){return this._iterator()},Mb.prototype.concat=function(){var a=this;return new pc(function(b){var c;try{c=a[N]()}catch(d){return b.onError(),void 0}var e,f=new yb,g=Db.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return b.onError(g),void 0}if(d.done)return b.onCompleted(),void 0;var h=d.value;J(h)&&(h=hc(h));var i=new xb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new rb(f,g,ub(function(){e=!0}))})},Mb.prototype.catchException=function(){var a=this;return new pc(function(b){var c;try{c=a[N]()}catch(d){return b.onError(),void 0}var e,f,g=new yb,h=Db.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return b.onError(h),void 0}if(d.done)return f?b.onError(f):b.onCompleted(),void 0;var i=d.value;J(i)&&(i=hc(i));var j=new xb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new rb(g,h,ub(function(){e=!0}))})};var Nb=Mb.repeat=function(a,b){return null==b&&(b=-1),new Mb(function(){var c=b;return new Lb(function(){return 0===c?P:(c>0&&c--,{done:!1,value:a})})})},Ob=Mb.forEach=function(a,b,c){return b||(b=E),new Mb(function(){var d=-1;return new Lb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return b.isAcquired=!1,void 0;c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Sb);Ub.create=Ub.createWithDisposable=function(a){return new pc(a)};var Wb=Ub.defer=function(a){return new pc(function(b){var c;try{c=a()}catch(d){return _b(d).subscribe(b)}return J(c)&&(c=hc(c)),c.subscribe(b)})},Xb=Ub.empty=function(a){return a||(a=Db),new pc(function(b){return a.schedule(function(){b.onCompleted()})})},Yb=Ub.fromArray=function(a,b){return b||(b=Eb),new pc(function(c){var d=0;return b.scheduleRecursive(function(b){dc?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Ub.repeat=function(a,b,c){return c||(c=Eb),null==b&&(b=-1),$b(a,c).repeat(b)};var $b=Ub["return"]=Ub.returnValue=function(a,b){return b||(b=Db),new pc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},_b=Ub["throw"]=Ub.throwException=function(a,b){return b||(b=Db),new pc(function(c){return b.schedule(function(){c.onError(a)})})};Rb["catch"]=Rb.catchException=function(a){return"function"==typeof a?m(this,a):ac([this,a])};var ac=Ub.catchException=Ub["catch"]=function(){var a=k(arguments,0);return Ob(a).catchException()};Rb.combineLatest=function(){var a=jb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),bc.apply(this,a)};var bc=Ub.combineLatest=function(){var a=jb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new pc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(E))){try{d=b.apply(null,k)}catch(e){return c.onError(e),void 0}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(E)&&c.onCompleted()}function e(a){j[a]=!0,j.every(E)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new xb;J(f)&&(f=hc(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new rb(m)})};Rb.concat=function(){var a=jb.call(arguments,0);return a.unshift(this),cc.apply(this,a)};var cc=Ub.concat=function(){var a=k(arguments,0);return Ob(a).concat()};Rb.concatObservable=Rb.concatAll=function(){return this.merge(1)},Rb.merge=function(a){if("number"!=typeof a)return dc(this,a);var b=this;return new pc(function(c){var d=0,e=new rb,f=!1,g=[],h=function(a){var b=new xb;e.add(b),J(a)&&(a=hc(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){var a;e.remove(b),g.length>0?(a=g.shift(),h(a)):(d--,f&&0===d&&c.onCompleted())}))};return e.add(b.subscribe(function(b){a>d?(d++,h(b)):g.push(b)},c.onError.bind(c),function(){f=!0,0===d&&c.onCompleted()})),e})};var dc=Ub.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=jb.call(arguments,1)):(a=Db,b=jb.call(arguments,0)):(a=Db,b=jb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Yb(b,a).mergeObservable()};Rb.mergeObservable=Rb.mergeAll=function(){var a=this;return new pc(function(b){var c=new rb,d=!1,e=new xb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new xb;c.add(e),J(a)&&(a=hc(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Rb.skipUntil=function(a){var b=this;return new pc(function(c){var d=!1,e=new rb(b.subscribe(function(a){d&&c.onNext(a)},c.onError.bind(c),function(){d&&c.onCompleted()})),f=new xb;return e.add(f),f.setDisposable(a.subscribe(function(){d=!0,f.dispose()},c.onError.bind(c),function(){f.dispose()})),e})},Rb["switch"]=Rb.switchLatest=function(){var a=this;return new pc(function(b){var c=!1,d=new yb,e=!1,f=0,g=a.subscribe(function(a){var g=new xb,h=++f;c=!0,d.setDisposable(g),J(a)&&(a=hc(a)),g.setDisposable(a.subscribe(function(a){f===h&&b.onNext(a)},function(a){f===h&&b.onError(a)},function(){f===h&&(c=!1,e&&b.onCompleted())}))},b.onError.bind(b),function(){e=!0,c||b.onCompleted()});return new rb(g,d)})},Rb.takeUntil=function(a){var b=this;return new pc(function(c){return new rb(b.subscribe(c),a.subscribe(c.onCompleted.bind(c),c.onError.bind(c),D))})},Rb.zip=function(){if(Array.isArray(arguments[0]))return n.apply(this,arguments);var a=this,b=jb.call(arguments),c=b.pop();return b.unshift(a),new pc(function(d){function e(b){var e,f;if(h.every(function(a){return a.length>0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return d.onError(g),void 0}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(E)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new xb;J(c)&&(c=hc(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new rb(j)})},Ub.zip=function(){var a=jb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Ub.zipArray=function(){var a=k(arguments,0);return new pc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(E))return b.onCompleted(),void 0}function d(a){return g[a]=!0,g.every(E)?(b.onCompleted(),void 0):void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new xb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new rb(h);return j.add(ub(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Rb.asObservable=function(){var a=this;return new pc(function(b){return a.subscribe(b)})},Rb.dematerialize=function(){var a=this;return new pc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Rb.distinctUntilChanged=function(a,b){var c=this;return a||(a=E),b||(b=G),new pc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return d.onError(i),void 0}if(f)try{h=b(e,g)}catch(i){return d.onError(i),void 0}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Rb["do"]=Rb.doAction=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new pc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Rb["finally"]=Rb.finallyAction=function(a){var b=this;return new pc(function(c){var d=b.subscribe(c);return ub(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Rb.ignoreElements=function(){var a=this;return new pc(function(b){return a.subscribe(D,b.onError.bind(b),b.onCompleted.bind(b))})},Rb.materialize=function(){var a=this;return new pc(function(b){return a.subscribe(function(a){b.onNext(Ib(a))},function(a){b.onNext(Jb(a)),b.onCompleted()},function(){b.onNext(Kb()),b.onCompleted()})})},Rb.repeat=function(a){return Nb(this,a).concat() +},Rb.retry=function(a){return Nb(this,a).catchException()},Rb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new pc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return e.onError(i),void 0}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Rb.skipLast=function(a){var b=this;return new pc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Rb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Db,a=jb.call(arguments,c),Ob([Yb(a,b),this]).concat()},Rb.takeLast=function(a,b){return this.takeLastBuffer(a).selectMany(function(a){return Yb(a,b)})},Rb.takeLastBuffer=function(a){var b=this;return new pc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Rb.select=Rb.map=function(a,b){var c=this;return new pc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.selectMany=Rb.flatMap=function(a,b){return b?this.selectMany(function(c,d){var e=a(c,d),f=J(e)?hc(e):e;return f.select(function(a){return b(c,a,d)})}):"function"==typeof a?o.call(this,a):o.call(this,function(){return a})},Rb.selectSwitch=Rb.flatMapLatest=function(a,b){return this.select(a,b).switchLatest()},Rb.skip=function(a){if(0>a)throw new Error(L);var b=this;return new pc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Rb.skipWhile=function(a,b){var c=this;return new pc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.take=function(a,b){if(0>a)throw new Error(L);if(0===a)return Xb(b);var c=this;return new pc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Rb.takeWhile=function(a,b){var c=this;return new pc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.where=Rb.filter=function(a,b){var c=this;return new pc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},Ub.fromCallback=function(a,b,c,d){return b||(b=Db),function(){var e=jb.call(arguments,0);return new pc(function(f){return b.schedule(function(){function b(a){var b=a;if(d)try{b=d(arguments)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}},Ub.fromNodeCallback=function(a,b,c,d){return b||(b=Db),function(){var e=jb.call(arguments,0);return new pc(function(f){return b.schedule(function(){function b(a){if(a)return f.onError(a),void 0;var b=jb.call(arguments,1);if(d)try{b=d(b)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}};var ec=x.angular&&angular.element?angular.element:x.jQuery?x.jQuery:x.Zepto?x.Zepto:null,fc=!!x.Ember&&"function"==typeof x.Ember.addListener;Ub.fromEvent=function(a,b,c){if(fc)return gc(function(){Ember.addListener(a,b)},function(){Ember.removeListener(a,b)},c);if(ec){var d=ec(a);return gc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}return new pc(function(d){return r(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)})}).publish().refCount()};var gc=Ub.fromEventPattern=function(a,b,c){return new pc(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)}var f=a(e);return ub(function(){b&&b(e,f)})}).publish().refCount()},hc=Ub.fromPromise=function(a){return new pc(function(b){return a.then(function(a){b.onNext(a),b.onCompleted()},function(a){b.onError(a)}),function(){a&&a.abort&&a.abort()}})};Rb.toPromise=function(a){if(a||(a=C.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Ub.startAsync=function(a){var b;try{b=a()}catch(c){return _b(c)}return hc(b)},Rb.multicast=function(a,b){var c=this;return"function"==typeof a?new pc(function(d){var e=c.multicast(a());return new rb(b(e).subscribe(d),e.connect())}):new ic(c,a)},Rb.publish=function(a){return a?this.multicast(function(){return new sc},a):this.multicast(new sc)},Rb.share=function(){return this.publish(null).refCount()},Rb.publishLast=function(a){return a?this.multicast(function(){return new tc},a):this.multicast(new tc)},Rb.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new vc(b)},a):this.multicast(new vc(a))},Rb.shareValue=function(a){return this.publishValue(a).refCount()},Rb.replay=function(a,b,c,d){return a?this.multicast(function(){return new wc(b,c,d)},a):this.multicast(new wc(b,c,d))},Rb.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var ic=C.ConnectableObservable=function(a){function b(b,c){function d(a){return e.subject.subscribe(a)}var e={subject:c,source:b.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return e.hasSubscription||(e.hasSubscription=!0,e.subscription=new rb(e.source.subscribe(e.subject),ub(function(){e.hasSubscription=!1}))),e.subscription},a.call(this,d)}return kb(b,a),b.prototype.connect=function(){return this.connect()},b.prototype.refCount=function(){var a=null,b=0,c=this;return new pc(function(d){var e,f;return b++,e=1===b,f=c.subscribe(d),e&&(a=c.connect()),ub(function(){f.dispose(),b--,0===b&&a.dispose()})})},b}(Ub),jc=Ub.interval=function(a,b){return b||(b=Gb),t(a,a,b)},kc=Ub.timer=function(b,c,d){var e;return d||(d=Gb),"number"==typeof c?e=c:"object"==typeof c&&"now"in c&&(d=c),e===a?s(b,d):t(b,e,d)};Rb.delay=function(a,b){b||(b=Gb);var c=this;return new pc(function(d){var e,f=!1,g=new yb,h=null,i=[],j=!1;return e=c.materialize().timestamp(b).subscribe(function(c){var e,k;"E"===c.value.kind?(i=[],i.push(c),h=c.value.exception,k=!j):(i.push({value:c.value,timestamp:c.timestamp+a}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new xb,g.setDisposable(e),e.setDisposable(b.scheduleRecursiveWithRelative(a,function(a){var c,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-b.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-b.now())):f=!1,c=h,j=!1,null!==c?d.onError(c):k&&a(e)}}))))}),new rb(e,g)})},Rb.throttle=function(a,b){b||(b=Gb);return this.throttleWithSelector(function(){return kc(a,b)})},Rb.timeInterval=function(a){var b=this;return a||(a=Gb),Wb(function(){var c=a.now();return b.select(function(b){var d=a.now(),e=d-c;return c=d,{value:b,interval:e}})})},Rb.timestamp=function(a){return a||(a=Gb),this.select(function(b){return{value:b,timestamp:a.now()}})},Rb.sample=function(a,b){return b||(b=Gb),"number"==typeof a?u(this,jc(a,b)):u(this,a)},Rb.timeout=function(a,b,c){var d,e=this;return b||(b=_b(new Error("Timeout"))),c||(c=Gb),d=a instanceof Date?function(a,b){c.scheduleWithAbsolute(a,b)}:function(a,b){c.scheduleWithRelative(a,b)},new pc(function(c){var f,g=0,h=new xb,i=new yb,j=!1,k=new yb;return i.setDisposable(h),f=function(){var e=g;k.setDisposable(d(a,function(){j=g===e;var a=j;a&&i.setDisposable(b.subscribe(c))}))},f(),h.setDisposable(e.subscribe(function(a){var b=!j;b&&(g++,c.onNext(a),f())},function(a){var b=!j;b&&(g++,c.onError(a))},function(){var a=!j;a&&(g++,c.onCompleted())})),new rb(i,k)})},Ub.generateWithRelativeTime=function(a,b,c,d,e,f){return f||(f=Gb),new pc(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithRelative(0,function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return g.onError(f),void 0}k?a(i):g.onCompleted()})})},Rb.delaySubscription=function(a,b){return b||(b=Gb),this.delayWithSelector(kc(a,b),function(){return Xb()})},Rb.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new pc(function(a){var b=new rb,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new yb,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return a.onError(f),void 0}var h=new xb;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new rb(h,b)})},Rb.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=Zb()}c||(c=_b(new Error("Timeout")));var d=this;return new pc(function(e){var f=new yb,g=new yb,h=new xb;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new xb;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return e.onError(d),void 0}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new rb(f,g)})},Rb.throttleWithSelector=function(a){var b=this;return new pc(function(c){var d,e=!1,f=new yb,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return c.onError(i),void 0}e=!0,d=b,g++;var j=g,k=new xb;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new rb(h,f)})},Rb.skipLastWithTime=function(a,b){b||(b=Gb);var c=this;return new pc(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},Rb.takeLastWithTime=function(a,b,c){return this.takeLastBufferWithTime(a,b).selectMany(function(a){return Yb(a,c)})},Rb.takeLastBufferWithTime=function(a,b){var c=this;return b||(b=Gb),new pc(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},Rb.takeWithTime=function(a,b){var c=this;return b||(b=Gb),new pc(function(d){var e=b.scheduleWithRelative(a,function(){d.onCompleted()});return new rb(e,c.subscribe(d))})},Rb.skipWithTime=function(a,b){var c=this;return b||(b=Gb),new pc(function(d){var e=!1,f=b.scheduleWithRelative(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new rb(f,g)})},Rb.skipUntilWithTime=function(a,b){b||(b=Gb);var c=this;return new pc(function(d){var e=!1,f=b.scheduleWithAbsolute(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new rb(f,g)})},Rb.takeUntilWithTime=function(a,b){b||(b=Gb);var c=this;return new pc(function(d){return new rb(b.scheduleWithAbsolute(a,function(){d.onCompleted()}),c.subscribe(d))})};var lc=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=vb,e=this.subject.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=vb)});return new rb(c,d,e)}function c(c,d){this.source=c,this.subject=d||new sc,this.isPaused=!0,a.call(this,b)}return kb(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(Ub);Rb.pausable=function(a){return new lc(this,a)};var mc=function(a){function b(a){var b=[],c=!0,d=v(this.source,this.subject.distinctUntilChanged(),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(d){if(d.shouldFire&&c&&a.onNext(d.data),d.shouldFire&&!c){for(;b.length>0;)a.onNext(b.shift());c=!0}else d.shouldFire||c?!d.shouldFire&&c&&(c=!1):b.push(d.data)},a.onError.bind(a),a.onCompleted.bind(a));return this.subject.onNext(!1),d}function c(c,d){this.source=c,this.subject=d||new sc,this.isPaused=!0,a.call(this,b)}return kb(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(Ub);Rb.pausableBuffered=function(a){return new mc(this,a)},Rb.controlled=function(a){return null==a&&(a=!0),new nc(this,a)};var nc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new oc(d),this.source=c.multicast(this.subject).refCount()}return kb(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(Ub),oc=C.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new sc,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=vb,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=vb}return kb(d,a),lb(d.prototype,Pb,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=vb):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=vb),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?vb:(this.requestedCount=a,this.requestedDisposable=ub(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=vb},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(Ub),pc=C.AnonymousObservable=function(a){function b(a){return"undefined"==typeof a?a=vb:"function"==typeof a&&(a=ub(a)),a}function c(d){function e(a){var c=new qc(a);if(Eb.scheduleRequired())Eb.schedule(function(){try{c.setDisposable(b(d(c)))}catch(a){if(!c.fail(a))throw a}});else try{c.setDisposable(b(d(c)))}catch(e){if(!c.fail(e))throw e}return c}return this instanceof c?(a.call(this,e),void 0):new c(d)}return kb(c,a),c}(Ub),qc=function(a){function b(b){a.call(this),this.observer=b,this.m=new xb}kb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Sb),rc=function(a,b){this.subject=a,this.observer=b};rc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var sc=C.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),vb):(a.onCompleted(),vb):(this.observers.push(a),new rc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return kb(d,a),lb(d.prototype,Pb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new uc(a,b)},d}(Ub),tc=C.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new rc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),vb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return kb(d,a),lb(d.prototype,Pb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Ub),uc=function(a){function b(a){return this.observable.subscribe(a)}function c(c,d){a.call(this,b),this.observer=c,this.observable=d}return kb(c,a),lb(c.prototype,Pb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),c}(Ub),vc=C.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new rc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),vb}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return kb(d,a),lb(d.prototype,Pb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(Ub),wc=C.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new Vb(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||Eb,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},kb(e,a),lb(e.prototype,Pb,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(Ub);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(x.Rx=C,define(function(){return C})):y&&z?A?(z.exports=C).Rx=C:y.Rx=C:x.Rx=C}).call(this); \ No newline at end of file diff --git a/js/libs/rxjs/rx.lite.js b/js/libs/rxjs/rx.lite.js new file mode 100644 index 0000000..0bb14ab --- /dev/null +++ b/js/libs/rxjs/rx.lite.js @@ -0,0 +1,5568 @@ +// 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 + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + 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.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + 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, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= 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) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + 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 () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (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; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, 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); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!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); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + 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) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + 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 (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @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)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + 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)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + /** + * @constructor + * @private + */ + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] 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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber; + if (typeof observerOrOnNext === 'object') { + subscriber = observerOrOnNext; + } else { + subscriber = observerCreate(observerOrOnNext, onError, onCompleted); + } + + return this._subscribe(subscriber); + }; + + /** + * Creates a list from an observable sequence. + * + * @memberOf Observable + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + function accumulator(list, i) { + var newList = list.slice(0); + newList.push(i); + return newList; + } + return this.scan([], accumulator).startWith([]).finalValue(); + }; + + return Observable; + })(); + + 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 (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + 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)); + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @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) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0; + return scheduler.scheduleRecursive(function (self) { + if (count < array.length) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * 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 AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * 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.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + if (isOpen) { + observer.onNext(left); + } + }, observer.onError.bind(observer), function () { + if (isOpen) { + observer.onCompleted(); + } + })); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * 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. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * 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 (observer) { + return source.subscribe(observer); + }); + }; + + /** + * 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. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @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.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = source.subscribe(observer); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + */ + 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(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + 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. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @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 the accumulated values. + */ + 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 AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @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. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + /** + * 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 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. + * @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. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * 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 = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; 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 that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * 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). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 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); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + var schedulerMethod, source = this; + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + if (dueTime instanceof Date) { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithAbsolute(dt, action); + }; + } else { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithRelative(dt, action); + }; + } + return new AnonymousObservable(function (observer) { + var createTimer, + id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + subscription.setDisposable(original); + createTimer = function () { + var myId = id; + timer.setDisposable(schedulerMethod(dueTime, function () { + switched = id === myId; + var timerWins = switched; + if (timerWins) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + createTimer(); + original.setDisposable(source.subscribe(function (x) { + var onNextWins = !switched; + if (onNextWins) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + var onErrorWins = !switched; + if (onErrorWins) { + id++; + observer.onError(e); + } + }, function () { + var onCompletedWins = !switched; + if (onCompletedWins) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + 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) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + 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(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer) + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * 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 {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (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.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + var AnonymousObservable = Rx.AnonymousObservable = (function (_super) { + inherits(AnonymousObservable, _super); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }); + } else { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + } + + return autoDetachObserver; + } + + _super.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + 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 noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + 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; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + 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. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _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(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/js/libs/rxjs/rx.lite.min.js b/js/libs/rxjs/rx.lite.min.js new file mode 100644 index 0000000..bda2793 --- /dev/null +++ b/js/libs/rxjs/rx.lite.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(L)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;gb.nonEnumArgs&&a.length&&h(a)&&(a=ib.call(a));var d=gb.enumPrototypes&&"function"==typeof a,e=gb.enumErrorProps&&(a===ab||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(gb.nonEnumShadows&&a!==bb){var g=a.constructor,i=-1,j=eb.length;if(a===(g&&g.prototype))var k=a===stringProto?Y:a===ab?T:Z.call(a),l=fb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:ib.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){return new mc(function(c){var d=new ub,e=new vb;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return c.onError(g),void 0}I(f)&&(f=ec(f)),d=new ub,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function n(a,b){var c=this;return new mc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return d.onError(i),void 0}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function o(a){return this.select(function(b,c){var d=a(b,c);return I(d)?ec(d):d}).mergeObservable()}function p(a,b,c){if(a.addListener)return a.addListener(b,c),rb(function(){a.removeListener(b,c)});if(a.addEventListener)return a.addEventListener(b,c,!1),rb(function(){a.removeEventListener(b,c,!1)});throw new Error("No listener found")}function q(a,b,c){var d=new ob;if("function"==typeof a.item&&"number"==typeof a.length)for(var e=0,f=a.length;f>e;e++)d.add(q(a.item(e),b,c));else a&&d.add(p(a,b,c));return d}function r(a,b){var c=zb(a);return new mc(function(a){return b.scheduleWithRelative(c,function(){a.onNext(0),a.onCompleted()})})}function s(a,b,c){return a===b?new mc(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):Tb(function(){return observableTimerDateAndPeriod(c.now()+a,b,c)})}function t(a,b){return new mc(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new ob(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}function u(a,b,c){return new mc(function(d){function e(a,b){j[b]=a;var e;if(g[b]=!0,h||(h=g.every(D))){try{e=c.apply(null,j)}catch(f){return d.onError(f),void 0}d.onNext(e)}else i&&d.onCompleted()}var f=2,g=[!1,!1],h=!1,i=!1,j=new Array(f);return new ob(a.subscribe(function(a){e(a,0)},d.onError.bind(d),function(){i=!0,d.onCompleted()}),b.subscribe(function(a){e(a,1)},d.onError.bind(d)))})}var v={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},w=v[typeof window]&&window||this,x=v[typeof exports]&&exports&&!exports.nodeType&&exports,y=v[typeof module]&&module&&!module.nodeType&&module,z=y&&y.exports===x&&x,A=v[typeof global]&&global;!A||A.global!==A&&A.window!==A||(w=A);var B={internals:{},config:{Promise:w.Promise},helpers:{}},C=B.helpers.noop=function(){},D=B.helpers.identity=function(a){return a},E=B.helpers.defaultNow=Date.now,F=B.helpers.defaultComparer=function(a,b){return hb(a,b)},G=B.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},H=(B.helpers.defaultKeySerializer=function(a){return a.toString()},B.helpers.defaultError=function(a){throw a}),I=B.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then&&a.then!==B.Observable.prototype.then},J=(B.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},B.helpers.not=function(a){return!a},"Sequence contains no elements."),K="Argument out of range",L="Object has been disposed",M="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";w.Set&&"function"==typeof(new w.Set)["@@iterator"]&&(M="@@iterator");var N,O={done:!0,value:a},P="[object Arguments]",Q="[object Array]",R="[object Boolean]",S="[object Date]",T="[object Error]",U="[object Function]",V="[object Number]",W="[object Object]",X="[object RegExp]",Y="[object String]",Z=Object.prototype.toString,$=Object.prototype.hasOwnProperty,_=Z.call(arguments)==P,ab=Error.prototype,bb=Object.prototype,cb=bb.propertyIsEnumerable;try{N=!(Z.call(document)==W&&!({toString:0}+""))}catch(db){N=!0}var eb=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],fb={};fb[Q]=fb[S]=fb[V]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},fb[R]=fb[Y]={constructor:!0,toString:!0,valueOf:!0},fb[T]=fb[U]=fb[X]={constructor:!0,toString:!0},fb[W]={constructor:!0};var gb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);gb.enumErrorProps=cb.call(ab,"message")||cb.call(ab,"name"),gb.enumPrototypes=cb.call(a,"prototype"),gb.nonEnumArgs=0!=c,gb.nonEnumShadows=!/valueOf/.test(b)}(1),_||(h=function(a){return a&&"object"==typeof a?$.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&Z.call(a)==U});var hb=B.internals.isEqual=function(a,b){return j(a,b,[],[])},ib=Array.prototype.slice,jb=({}.hasOwnProperty,this.inherits=B.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),kb=B.internals.addProperties=function(a){for(var b=ib.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},lb=(B.internals.addRef=function(a,b){return new mc(function(c){return new ob(b.getDisposable(),a.subscribe(c))})},function(a,b){this.id=a,this.value=b});lb.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var mb=B.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},nb=mb.prototype;nb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},nb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},nb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},pb.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},pb.contains=function(a){return-1!==this.disposables.indexOf(a)},pb.toArray=function(){return this.disposables.slice(0)};var qb=B.Disposable=function(a){this.isDisposed=!1,this.action=a||C};qb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var rb=qb.create=function(a){return new qb(a)},sb=qb.empty={dispose:C},tb=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),ub=B.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return jb(b,a),b}(tb),vb=B.SerialDisposable=function(a){function b(){a.call(this,!1)}return jb(b,a),b}(tb),wb=(B.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?sb:new a(this)},b}(),B.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||G,this.disposable=new ub});wb.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},wb.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},wb.prototype.isCancelled=function(){return this.disposable.isDisposed},wb.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var xb,yb=B.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new ob,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),sb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new ob,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),sb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),sb}var e=a.prototype;return e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return rb(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=E,a.normalize=function(a){return 0>a&&(a=0),a},a}(),zb=yb.normalize,Ab=yb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=zb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new yb(E,a,b,c)}(),Bb=yb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-yb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+yb.normalize(c),g=new wb(this,b,d,f);if(e)e.enqueue(g);else{e=new mb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new yb(E,b,c,d);return f.scheduleRequired=function(){return null===e},f.ensureTrampoline=function(a){return null===e?this.schedule(a):a()},f}(),Cb=(B.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new ub;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),C);!function(){function a(){if(!w.postMessage||w.importScripts)return!1;var a=!1,b=w.onmessage;return w.onmessage=function(){a=!0},w.postMessage("","*"),w.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(Z).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=A&&z&&A.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=A&&z&&A.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))xb=process.nextTick;else if("function"==typeof d)xb=d,Cb=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;w.addEventListener?w.addEventListener("message",b,!1):w.attachEvent("onmessage",b,!1),xb=function(a){var b=h++;g[b]=a,w.postMessage(f+b,"*")}}else if(w.MessageChannel){var i=new w.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},xb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in w&&"onreadystatechange"in w.document.createElement("script")?xb=function(a){var b=w.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},w.document.documentElement.appendChild(b)}:(xb=function(a){return setTimeout(a,0)},Cb=clearTimeout)}();var Db=yb.timeout=function(){function a(a,b){var c=this,d=new ub,e=xb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new ob(d,rb(function(){Cb(e)}))}function b(a,b,c){var d=this,e=yb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new ub,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new ob(f,rb(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new yb(E,a,b,c)}(),Eb=B.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}var b=a.prototype;return b.accept=function(a,b,c){return 1===arguments.length&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},b.toObservable=function(a){var b=this;return a||(a=Ab),new mc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Fb=Eb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Eb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Gb=Eb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Eb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Hb=Eb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Eb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Ib=B.internals.Enumerator=function(a){this._next=a};Ib.prototype.next=function(){return this._next()},Ib.prototype[M]=function(){return this};var Jb=B.internals.Enumerable=function(a){this._iterator=a};Jb.prototype[M]=function(){return this._iterator()},Jb.prototype.concat=function(){var a=this;return new mc(function(b){var c;try{c=a[M]()}catch(d){return b.onError(),void 0}var e,f=new vb,g=Ab.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return b.onError(g),void 0}if(d.done)return b.onCompleted(),void 0;var h=d.value;I(h)&&(h=ec(h));var i=new ub;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new ob(f,g,rb(function(){e=!0}))})},Jb.prototype.catchException=function(){var a=this;return new mc(function(b){var c;try{c=a[M]()}catch(d){return b.onError(),void 0}var e,f,g=new vb,h=Ab.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return b.onError(h),void 0}if(d.done)return f?b.onError(f):b.onCompleted(),void 0;var i=d.value;I(i)&&(i=ec(i));var j=new ub;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new ob(g,h,rb(function(){e=!0}))})};var Kb=Jb.repeat=function(a,b){return null==b&&(b=-1),new Jb(function(){var c=b;return new Ib(function(){return 0===c?O:(c>0&&c--,{done:!1,value:a})})})},Lb=Jb.forEach=function(a,b,c){return b||(b=D),new Jb(function(){var d=-1;return new Ib(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return b.isAcquired=!1,void 0;c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Pb);Rb.create=Rb.createWithDisposable=function(a){return new mc(a)};var Tb=Rb.defer=function(a){return new mc(function(b){var c;try{c=a()}catch(d){return Yb(d).subscribe(b)}return I(c)&&(c=ec(c)),c.subscribe(b)})},Ub=Rb.empty=function(a){return a||(a=Ab),new mc(function(b){return a.schedule(function(){b.onCompleted()})})},Vb=Rb.fromArray=function(a,b){return b||(b=Bb),new mc(function(c){var d=0;return b.scheduleRecursive(function(b){dc?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Rb.repeat=function(a,b,c){return c||(c=Bb),null==b&&(b=-1),Xb(a,c).repeat(b)};var Xb=Rb["return"]=Rb.returnValue=function(a,b){return b||(b=Ab),new mc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},Yb=Rb["throw"]=Rb.throwException=function(a,b){return b||(b=Ab),new mc(function(c){return b.schedule(function(){c.onError(a)})})};Ob["catch"]=Ob.catchException=function(a){return"function"==typeof a?m(this,a):Zb([this,a])};var Zb=Rb.catchException=Rb["catch"]=function(){var a=k(arguments,0);return Lb(a).catchException()};Ob.combineLatest=function(){var a=ib.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),$b.apply(this,a)};var $b=Rb.combineLatest=function(){var a=ib.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new mc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(D))){try{d=b.apply(null,k)}catch(e){return c.onError(e),void 0}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(D)&&c.onCompleted()}function e(a){j[a]=!0,j.every(D)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new ub;I(f)&&(f=ec(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new ob(m)})};Ob.concat=function(){var a=ib.call(arguments,0);return a.unshift(this),_b.apply(this,a)};var _b=Rb.concat=function(){var a=k(arguments,0);return Lb(a).concat()};Ob.concatObservable=Ob.concatAll=function(){return this.merge(1)},Ob.merge=function(a){if("number"!=typeof a)return ac(this,a);var b=this;return new mc(function(c){var d=0,e=new ob,f=!1,g=[],h=function(a){var b=new ub;e.add(b),I(a)&&(a=ec(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){var a;e.remove(b),g.length>0?(a=g.shift(),h(a)):(d--,f&&0===d&&c.onCompleted())}))};return e.add(b.subscribe(function(b){a>d?(d++,h(b)):g.push(b)},c.onError.bind(c),function(){f=!0,0===d&&c.onCompleted()})),e})};var ac=Rb.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=ib.call(arguments,1)):(a=Ab,b=ib.call(arguments,0)):(a=Ab,b=ib.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Vb(b,a).mergeObservable()};Ob.mergeObservable=Ob.mergeAll=function(){var a=this;return new mc(function(b){var c=new ob,d=!1,e=new ub;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new ub;c.add(e),I(a)&&(a=ec(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Ob.skipUntil=function(a){var b=this;return new mc(function(c){var d=!1,e=new ob(b.subscribe(function(a){d&&c.onNext(a)},c.onError.bind(c),function(){d&&c.onCompleted()})),f=new ub;return e.add(f),f.setDisposable(a.subscribe(function(){d=!0,f.dispose()},c.onError.bind(c),function(){f.dispose()})),e})},Ob["switch"]=Ob.switchLatest=function(){var a=this;return new mc(function(b){var c=!1,d=new vb,e=!1,f=0,g=a.subscribe(function(a){var g=new ub,h=++f;c=!0,d.setDisposable(g),I(a)&&(a=ec(a)),g.setDisposable(a.subscribe(function(a){f===h&&b.onNext(a)},function(a){f===h&&b.onError(a)},function(){f===h&&(c=!1,e&&b.onCompleted())}))},b.onError.bind(b),function(){e=!0,c||b.onCompleted()});return new ob(g,d)})},Ob.takeUntil=function(a){var b=this;return new mc(function(c){return new ob(b.subscribe(c),a.subscribe(c.onCompleted.bind(c),c.onError.bind(c),C))})},Ob.zip=function(){if(Array.isArray(arguments[0]))return n.apply(this,arguments);var a=this,b=ib.call(arguments),c=b.pop();return b.unshift(a),new mc(function(d){function e(b){var e,f;if(h.every(function(a){return a.length>0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return d.onError(g),void 0}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(D)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new ub;I(c)&&(c=ec(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new ob(j)})},Rb.zip=function(){var a=ib.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Rb.zipArray=function(){var a=k(arguments,0);return new mc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(D))return b.onCompleted(),void 0}function d(a){return g[a]=!0,g.every(D)?(b.onCompleted(),void 0):void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new ub,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new ob(h);return j.add(rb(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Ob.asObservable=function(){var a=this;return new mc(function(b){return a.subscribe(b)})},Ob.dematerialize=function(){var a=this;return new mc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Ob.distinctUntilChanged=function(a,b){var c=this;return a||(a=D),b||(b=F),new mc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return d.onError(i),void 0}if(f)try{h=b(e,g)}catch(i){return d.onError(i),void 0}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Ob["do"]=Ob.doAction=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new mc(function(a){return e.subscribe(function(b){try{d(b)}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Ob["finally"]=Ob.finallyAction=function(a){var b=this;return new mc(function(c){var d=b.subscribe(c);return rb(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Ob.ignoreElements=function(){var a=this;return new mc(function(b){return a.subscribe(C,b.onError.bind(b),b.onCompleted.bind(b))})},Ob.materialize=function(){var a=this;return new mc(function(b){return a.subscribe(function(a){b.onNext(Fb(a))},function(a){b.onNext(Gb(a)),b.onCompleted()},function(){b.onNext(Hb()),b.onCompleted()})})},Ob.repeat=function(a){return Kb(this,a).concat()},Ob.retry=function(a){return Kb(this,a).catchException()},Ob.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new mc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return e.onError(i),void 0}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Ob.skipLast=function(a){var b=this;return new mc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Ob.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=Ab,a=ib.call(arguments,c),Lb([Vb(a,b),this]).concat()},Ob.takeLast=function(a,b){return this.takeLastBuffer(a).selectMany(function(a){return Vb(a,b)})},Ob.takeLastBuffer=function(a){var b=this;return new mc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Ob.select=Ob.map=function(a,b){var c=this;return new mc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.selectMany=Ob.flatMap=function(a,b){return b?this.selectMany(function(c,d){var e=a(c,d),f=I(e)?ec(e):e;return f.select(function(a){return b(c,a,d)})}):"function"==typeof a?o.call(this,a):o.call(this,function(){return a})},Ob.selectSwitch=Ob.flatMapLatest=function(a,b){return this.select(a,b).switchLatest()},Ob.skip=function(a){if(0>a)throw new Error(K);var b=this;return new mc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Ob.skipWhile=function(a,b){var c=this;return new mc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.take=function(a,b){if(0>a)throw new Error(K);if(0===a)return Ub(b);var c=this;return new mc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Ob.takeWhile=function(a,b){var c=this;return new mc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c) +}catch(h){return d.onError(h),void 0}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Ob.where=Ob.filter=function(a,b){var c=this;return new mc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})},Rb.fromCallback=function(a,b,c,d){return b||(b=Ab),function(){var e=ib.call(arguments,0);return new mc(function(f){return b.schedule(function(){function b(a){var b=a;if(d)try{b=d(arguments)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}},Rb.fromNodeCallback=function(a,b,c,d){return b||(b=Ab),function(){var e=ib.call(arguments,0);return new mc(function(f){return b.schedule(function(){function b(a){if(a)return f.onError(a),void 0;var b=ib.call(arguments,1);if(d)try{b=d(b)}catch(c){return f.onError(c),void 0}else 1===b.length&&(b=b[0]);f.onNext(b),f.onCompleted()}e.push(b),a.apply(c,e)})})}};var bc=w.angular&&angular.element?angular.element:w.jQuery?w.jQuery:w.Zepto?w.Zepto:null,cc=!!w.Ember&&"function"==typeof w.Ember.addListener;Rb.fromEvent=function(a,b,c){if(cc)return dc(function(){Ember.addListener(a,b)},function(){Ember.removeListener(a,b)},c);if(bc){var d=bc(a);return dc(function(a){d.on(b,a)},function(a){d.off(b,a)},c)}return new mc(function(d){return q(a,b,function(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)})}).publish().refCount()};var dc=Rb.fromEventPattern=function(a,b,c){return new mc(function(d){function e(a){var b=a;if(c)try{b=c(arguments)}catch(e){return d.onError(e),void 0}d.onNext(b)}var f=a(e);return rb(function(){b&&b(e,f)})}).publish().refCount()},ec=Rb.fromPromise=function(a){return new mc(function(b){return a.then(function(a){b.onNext(a),b.onCompleted()},function(a){b.onError(a)}),function(){a&&a.abort&&a.abort()}})};Ob.toPromise=function(a){if(a||(a=B.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Rb.startAsync=function(a){var b;try{b=a()}catch(c){return Yb(c)}return ec(b)},Ob.multicast=function(a,b){var c=this;return"function"==typeof a?new mc(function(d){var e=c.multicast(a());return new ob(b(e).subscribe(d),e.connect())}):new fc(c,a)},Ob.publish=function(a){return a?this.multicast(function(){return new pc},a):this.multicast(new pc)},Ob.share=function(){return this.publish(null).refCount()},Ob.publishLast=function(a){return a?this.multicast(function(){return new qc},a):this.multicast(new qc)},Ob.publishValue=function(a,b){return 2===arguments.length?this.multicast(function(){return new sc(b)},a):this.multicast(new sc(a))},Ob.shareValue=function(a){return this.publishValue(a).refCount()},Ob.replay=function(a,b,c,d){return a?this.multicast(function(){return new tc(b,c,d)},a):this.multicast(new tc(b,c,d))},Ob.shareReplay=function(a,b,c){return this.replay(null,a,b,c).refCount()};var fc=B.ConnectableObservable=function(a){function b(b,c){function d(a){return e.subject.subscribe(a)}var e={subject:c,source:b.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return e.hasSubscription||(e.hasSubscription=!0,e.subscription=new ob(e.source.subscribe(e.subject),rb(function(){e.hasSubscription=!1}))),e.subscription},a.call(this,d)}return jb(b,a),b.prototype.connect=function(){return this.connect()},b.prototype.refCount=function(){var a=null,b=0,c=this;return new mc(function(d){var e,f;return b++,e=1===b,f=c.subscribe(d),e&&(a=c.connect()),rb(function(){f.dispose(),b--,0===b&&a.dispose()})})},b}(Rb),gc=Rb.interval=function(a,b){return b||(b=Db),s(a,a,b)},hc=Rb.timer=function(b,c,d){var e;return d||(d=Db),"number"==typeof c?e=c:"object"==typeof c&&"now"in c&&(d=c),e===a?r(b,d):s(b,e,d)};Ob.delay=function(a,b){b||(b=Db);var c=this;return new mc(function(d){var e,f=!1,g=new vb,h=null,i=[],j=!1;return e=c.materialize().timestamp(b).subscribe(function(c){var e,k;"E"===c.value.kind?(i=[],i.push(c),h=c.value.exception,k=!j):(i.push({value:c.value,timestamp:c.timestamp+a}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new ub,g.setDisposable(e),e.setDisposable(b.scheduleRecursiveWithRelative(a,function(a){var c,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-b.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-b.now())):f=!1,c=h,j=!1,null!==c?d.onError(c):k&&a(e)}}))))}),new ob(e,g)})},Ob.throttle=function(a,b){b||(b=Db);return this.throttleWithSelector(function(){return hc(a,b)})},Ob.timeInterval=function(a){var b=this;return a||(a=Db),Tb(function(){var c=a.now();return b.select(function(b){var d=a.now(),e=d-c;return c=d,{value:b,interval:e}})})},Ob.timestamp=function(a){return a||(a=Db),this.select(function(b){return{value:b,timestamp:a.now()}})},Ob.sample=function(a,b){return b||(b=Db),"number"==typeof a?t(this,gc(a,b)):t(this,a)},Ob.timeout=function(a,b,c){var d,e=this;return b||(b=Yb(new Error("Timeout"))),c||(c=Db),d=a instanceof Date?function(a,b){c.scheduleWithAbsolute(a,b)}:function(a,b){c.scheduleWithRelative(a,b)},new mc(function(c){var f,g=0,h=new ub,i=new vb,j=!1,k=new vb;return i.setDisposable(h),f=function(){var e=g;k.setDisposable(d(a,function(){j=g===e;var a=j;a&&i.setDisposable(b.subscribe(c))}))},f(),h.setDisposable(e.subscribe(function(a){var b=!j;b&&(g++,c.onNext(a),f())},function(a){var b=!j;b&&(g++,c.onError(a))},function(){var a=!j;a&&(g++,c.onCompleted())})),new ob(i,k)})},Rb.generateWithRelativeTime=function(a,b,c,d,e,f){return f||(f=Db),new mc(function(g){var h,i,j=!0,k=!1,l=a;return f.scheduleRecursiveWithRelative(0,function(a){k&&g.onNext(h);try{j?j=!1:l=c(l),k=b(l),k&&(h=d(l),i=e(l))}catch(f){return g.onError(f),void 0}k?a(i):g.onCompleted()})})},Ob.delaySubscription=function(a,b){return b||(b=Db),this.delayWithSelector(hc(a,b),function(){return Ub()})},Ob.delayWithSelector=function(a,b){var c,d,e=this;return"function"==typeof a?d=a:(c=a,d=b),new mc(function(a){var b=new ob,f=!1,g=function(){f&&0===b.length&&a.onCompleted()},h=new vb,i=function(){h.setDisposable(e.subscribe(function(c){var e;try{e=d(c)}catch(f){return a.onError(f),void 0}var h=new ub;b.add(h),h.setDisposable(e.subscribe(function(){a.onNext(c),b.remove(h),g()},a.onError.bind(a),function(){a.onNext(c),b.remove(h),g()}))},a.onError.bind(a),function(){f=!0,h.dispose(),g()}))};return c?h.setDisposable(c.subscribe(function(){i()},a.onError.bind(a),function(){i()})):i(),new ob(h,b)})},Ob.timeoutWithSelector=function(a,b,c){if(1===arguments.length){b=a;var a=Wb()}c||(c=Yb(new Error("Timeout")));var d=this;return new mc(function(e){var f=new vb,g=new vb,h=new ub;f.setDisposable(h);var i=0,j=!1,k=function(a){var b=i,d=function(){return i===b},h=new ub;g.setDisposable(h),h.setDisposable(a.subscribe(function(){d()&&f.setDisposable(c.subscribe(e)),h.dispose()},function(a){d()&&e.onError(a)},function(){d()&&f.setDisposable(c.subscribe(e))}))};k(a);var l=function(){var a=!j;return a&&i++,a};return h.setDisposable(d.subscribe(function(a){if(l()){e.onNext(a);var c;try{c=b(a)}catch(d){return e.onError(d),void 0}k(c)}},function(a){l()&&e.onError(a)},function(){l()&&e.onCompleted()})),new ob(f,g)})},Ob.throttleWithSelector=function(a){var b=this;return new mc(function(c){var d,e=!1,f=new vb,g=0,h=b.subscribe(function(b){var h;try{h=a(b)}catch(i){return c.onError(i),void 0}e=!0,d=b,g++;var j=g,k=new ub;f.setDisposable(k),k.setDisposable(h.subscribe(function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()},c.onError.bind(c),function(){e&&g===j&&c.onNext(d),e=!1,k.dispose()}))},function(a){f.dispose(),c.onError(a),e=!1,g++},function(){f.dispose(),e&&c.onNext(d),c.onCompleted(),e=!1,g++});return new ob(h,f)})},Ob.skipLastWithTime=function(a,b){b||(b=Db);var c=this;return new mc(function(d){var e=[];return c.subscribe(function(c){var f=b.now();for(e.push({interval:f,value:c});e.length>0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},Ob.takeLastWithTime=function(a,b,c){return this.takeLastBufferWithTime(a,b).selectMany(function(a){return Vb(a,c)})},Ob.takeLastBufferWithTime=function(a,b){var c=this;return b||(b=Db),new mc(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},Ob.takeWithTime=function(a,b){var c=this;return b||(b=Db),new mc(function(d){var e=b.scheduleWithRelative(a,function(){d.onCompleted()});return new ob(e,c.subscribe(d))})},Ob.skipWithTime=function(a,b){var c=this;return b||(b=Db),new mc(function(d){var e=!1,f=b.scheduleWithRelative(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new ob(f,g)})},Ob.skipUntilWithTime=function(a,b){b||(b=Db);var c=this;return new mc(function(d){var e=!1,f=b.scheduleWithAbsolute(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new ob(f,g)})},Ob.takeUntilWithTime=function(a,b){b||(b=Db);var c=this;return new mc(function(d){return new ob(b.scheduleWithAbsolute(a,function(){d.onCompleted()}),c.subscribe(d))})};var ic=function(a){function b(a){var b=this.source.publish(),c=b.subscribe(a),d=sb,e=this.subject.distinctUntilChanged().subscribe(function(a){a?d=b.connect():(d.dispose(),d=sb)});return new ob(c,d,e)}function c(c,d){this.source=c,this.subject=d||new pc,this.isPaused=!0,a.call(this,b)}return jb(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(Rb);Ob.pausable=function(a){return new ic(this,a)};var jc=function(a){function b(a){var b=[],c=!0,d=u(this.source,this.subject.distinctUntilChanged(),function(a,b){return{data:a,shouldFire:b}}).subscribe(function(d){if(d.shouldFire&&c&&a.onNext(d.data),d.shouldFire&&!c){for(;b.length>0;)a.onNext(b.shift());c=!0}else d.shouldFire||c?!d.shouldFire&&c&&(c=!1):b.push(d.data)},a.onError.bind(a),a.onCompleted.bind(a));return this.subject.onNext(!1),d}function c(c,d){this.source=c,this.subject=d||new pc,this.isPaused=!0,a.call(this,b)}return jb(c,a),c.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},c.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},c}(Rb);Ob.pausableBuffered=function(a){return new jc(this,a)},Ob.controlled=function(a){return null==a&&(a=!0),new kc(this,a)};var kc=function(a){function b(a){return this.source.subscribe(a)}function c(c,d){a.call(this,b),this.subject=new lc(d),this.source=c.multicast(this.subject).refCount()}return jb(c,a),c.prototype.request=function(a){return null==a&&(a=-1),this.subject.request(a)},c}(Rb),lc=B.ControlledSubject=function(a){function c(a){return this.subject.subscribe(a)}function d(b){null==b&&(b=!0),a.call(this,c),this.subject=new pc,this.enableQueue=b,this.queue=b?[]:null,this.requestedCount=0,this.requestedDisposable=sb,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=sb}return jb(d,a),kb(d.prototype,Mb,{onCompleted:function(){b.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(a){b.call(this),this.hasFailed=!0,this.error=a,this.enableQueue&&0!==this.queue.length||this.subject.onError(a)},onNext:function(a){b.call(this);var c=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(a):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),c=!0),c&&this.subject.onNext(a)},_processRequest:function(a){if(this.enableQueue){for(;this.queue.length>=a&&a>0;)this.subject.onNext(this.queue.shift()),a--;return 0!==this.queue.length?{numberOfItems:a,returnValue:!0}:{numberOfItems:a,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=sb):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=sb),{numberOfItems:a,returnValue:!1}},request:function(a){b.call(this),this.disposeCurrentRequest();var c=this,d=this._processRequest(a);return a=d.numberOfItems,d.returnValue?sb:(this.requestedCount=a,this.requestedDisposable=rb(function(){c.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=sb},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),d}(Rb),mc=B.AnonymousObservable=function(a){function b(a){return"undefined"==typeof a?a=sb:"function"==typeof a&&(a=rb(a)),a}function c(d){function e(a){var c=new nc(a);if(Bb.scheduleRequired())Bb.schedule(function(){try{c.setDisposable(b(d(c)))}catch(a){if(!c.fail(a))throw a}});else try{c.setDisposable(b(d(c)))}catch(e){if(!c.fail(e))throw e}return c}return this instanceof c?(a.call(this,e),void 0):new c(d)}return jb(c,a),c}(Rb),nc=function(a){function b(b){a.call(this),this.observer=b,this.m=new ub}jb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Pb),oc=function(a,b){this.subject=a,this.observer=b};oc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var pc=B.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),sb):(a.onCompleted(),sb):(this.observers.push(a),new oc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return jb(d,a),kb(d.prototype,Mb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new rc(a,b)},d}(Rb),qc=B.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new oc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),sb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return jb(d,a),kb(d.prototype,Mb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Rb),rc=function(a){function b(a){return this.observable.subscribe(a)}function c(c,d){a.call(this,b),this.observer=c,this.observable=d}return jb(c,a),kb(c.prototype,Mb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),c}(Rb),sc=B.BehaviorSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),a.onNext(this.value),new oc(this,a);var c=this.exception;return c?a.onError(c):a.onCompleted(),sb}function d(b){a.call(this,c),this.value=b,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return jb(d,a),kb(d.prototype,Mb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped){this.value=a;for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),d}(Rb),tc=B.ReplaySubject=function(a){function c(a,b){this.subject=a,this.observer=b}function d(a){var d=new Sb(this.scheduler,a),e=new c(this,d);b.call(this),this._trim(this.scheduler.now()),this.observers.push(d);for(var f=this.q.length,g=0,h=this.q.length;h>g;g++)d.onNext(this.q[g].value);return this.hasError?(f++,d.onError(this.error)):this.isStopped&&(f++,d.onCompleted()),d.ensureActive(f),e}function e(b,c,e){this.bufferSize=null==b?Number.MAX_VALUE:b,this.windowSize=null==c?Number.MAX_VALUE:c,this.scheduler=e||Bb,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,a.call(this,d)}return c.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1)}},jb(e,a),kb(e.prototype,Mb,{hasObservers:function(){return this.observers.length>0},_trim:function(a){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&a-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(a){var c;if(b.call(this),!this.isStopped){var d=this.scheduler.now();this.q.push({interval:d,value:a}),this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onNext(a),c.ensureActive()}},onError:function(a){var c;if(b.call(this),!this.isStopped){this.isStopped=!0,this.error=a,this.hasError=!0;var d=this.scheduler.now();this._trim(d);for(var e=this.observers.slice(0),f=0,g=e.length;g>f;f++)c=e[f],c.onError(a),c.ensureActive();this.observers=[]}},onCompleted:function(){var a;if(b.call(this),!this.isStopped){this.isStopped=!0;var c=this.scheduler.now();this._trim(c);for(var d=this.observers.slice(0),e=0,f=d.length;f>e;e++)a=d[e],a.onCompleted(),a.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),e}(Rb);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(w.Rx=B,define(function(){return B})):x&&y?z?(y.exports=B).Rx=B:x.Rx=B:w.Rx=B}).call(this); \ No newline at end of file diff --git a/js/libs/rxjs/rx.min.js b/js/libs/rxjs/rx.min.js new file mode 100644 index 0000000..8c78242 --- /dev/null +++ b/js/libs/rxjs/rx.min.js @@ -0,0 +1,2 @@ +(function(a){function b(){if(this.isDisposed)throw new Error(H)}function c(a){var b=typeof a;return a&&("function"==b||"object"==b)||!1}function d(a){var b=[];if(!c(a))return b;cb.nonEnumArgs&&a.length&&h(a)&&(a=eb.call(a));var d=cb.enumPrototypes&&"function"==typeof a,e=cb.enumErrorProps&&(a===Y||a instanceof Error);for(var f in a)d&&"prototype"==f||e&&("message"==f||"name"==f)||b.push(f);if(cb.nonEnumShadows&&a!==Z){var g=a.constructor,i=-1,j=ab.length;if(a===(g&&g.prototype))var k=a===stringProto?U:a===Y?P:V.call(a),l=bb[k];for(;++i-1:void 0});return c.pop(),d.pop(),result}function k(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:eb.call(a)}function l(a,b){for(var c=new Array(a),d=0;a>d;d++)c[d]=b();return c}function m(a,b){this.scheduler=a,this.disposable=b,this.isDisposed=!1}function n(a,b){return new cc(function(c){var d=new rb,e=new sb;return e.setDisposable(d),d.setDisposable(a.subscribe(c.onNext.bind(c),function(a){var d,f;try{f=b(a)}catch(g){return c.onError(g),void 0}E(f)&&(f=Tb(f)),d=new rb,e.setDisposable(d),d.setDisposable(f.subscribe(c))},c.onCompleted.bind(c))),e})}function o(a,b){var c=this;return new cc(function(d){var e=0,f=a.length;return c.subscribe(function(c){if(f>e){var g,h=a[e++];try{g=b(c,h)}catch(i){return d.onError(i),void 0}d.onNext(g)}else d.onCompleted()},d.onError.bind(d),d.onCompleted.bind(d))})}function p(a){return this.select(function(b,c){var d=a(b,c);return E(d)?Tb(d):d}).mergeObservable()}var q={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},r=q[typeof window]&&window||this,s=q[typeof exports]&&exports&&!exports.nodeType&&exports,t=q[typeof module]&&module&&!module.nodeType&&module,u=t&&t.exports===s&&s,v=q[typeof global]&&global;!v||v.global!==v&&v.window!==v||(r=v);var w={internals:{},config:{Promise:r.Promise},helpers:{}},x=w.helpers.noop=function(){},y=w.helpers.identity=function(a){return a},z=w.helpers.defaultNow=Date.now,A=w.helpers.defaultComparer=function(a,b){return db(a,b)},B=w.helpers.defaultSubComparer=function(a,b){return a>b?1:b>a?-1:0},C=w.helpers.defaultKeySerializer=function(a){return a.toString()},D=w.helpers.defaultError=function(a){throw a},E=w.helpers.isPromise=function(a){return!!a&&"function"==typeof a.then&&a.then!==w.Observable.prototype.then},F=(w.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},w.helpers.not=function(a){return!a},"Sequence contains no elements."),G="Argument out of range",H="Object has been disposed",I="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";r.Set&&"function"==typeof(new r.Set)["@@iterator"]&&(I="@@iterator");var J,K={done:!0,value:a},L="[object Arguments]",M="[object Array]",N="[object Boolean]",O="[object Date]",P="[object Error]",Q="[object Function]",R="[object Number]",S="[object Object]",T="[object RegExp]",U="[object String]",V=Object.prototype.toString,W=Object.prototype.hasOwnProperty,X=V.call(arguments)==L,Y=Error.prototype,Z=Object.prototype,$=Z.propertyIsEnumerable;try{J=!(V.call(document)==S&&!({toString:0}+""))}catch(_){J=!0}var ab=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bb={};bb[M]=bb[O]=bb[R]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},bb[N]=bb[U]={constructor:!0,toString:!0,valueOf:!0},bb[P]=bb[Q]=bb[T]={constructor:!0,toString:!0},bb[S]={constructor:!0};var cb={};!function(){var a=function(){this.x=1},b=[];a.prototype={valueOf:1,y:1};for(var c in new a)b.push(c);for(c in arguments);cb.enumErrorProps=$.call(Y,"message")||$.call(Y,"name"),cb.enumPrototypes=$.call(a,"prototype"),cb.nonEnumArgs=0!=c,cb.nonEnumShadows=!/valueOf/.test(b)}(1),X||(h=function(a){return a&&"object"==typeof a?W.call(a,"callee"):!1}),i(/x/)&&(i=function(a){return"function"==typeof a&&V.call(a)==Q});var db=w.internals.isEqual=function(a,b){return j(a,b,[],[])},eb=Array.prototype.slice,fb=({}.hasOwnProperty,this.inherits=w.internals.inherits=function(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}),gb=w.internals.addProperties=function(a){for(var b=eb.call(arguments,1),c=0,d=b.length;d>c;c++){var e=b[c];for(var f in e)a[f]=e[f]}},hb=w.internals.addRef=function(a,b){return new cc(function(c){return new lb(b.getDisposable(),a.subscribe(c))})},ib=function(a,b){this.id=a,this.value=b};ib.prototype.compareTo=function(a){var b=this.value.compareTo(a.value);return 0===b&&(b=this.id-a.id),b};var jb=w.internals.PriorityQueue=function(a){this.items=new Array(a),this.length=0},kb=jb.prototype;kb.isHigherPriority=function(a,b){return this.items[a].compareTo(this.items[b])<0},kb.percolate=function(a){if(!(a>=this.length||0>a)){var b=a-1>>1;if(!(0>b||b===a)&&this.isHigherPriority(a,b)){var c=this.items[a];this.items[a]=this.items[b],this.items[b]=c,this.percolate(b)}}},kb.heapify=function(b){if(b===a&&(b=0),!(b>=this.length||0>b)){var c=2*b+1,d=2*b+2,e=b;if(cb;b++)a[b].dispose()}},mb.clear=function(){var a=this.disposables.slice(0);this.disposables=[],this.length=0;for(var b=0,c=a.length;c>b;b++)a[b].dispose()},mb.contains=function(a){return-1!==this.disposables.indexOf(a)},mb.toArray=function(){return this.disposables.slice(0)};var nb=w.Disposable=function(a){this.isDisposed=!1,this.action=a||x};nb.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ob=nb.create=function(a){return new nb(a)},pb=nb.empty={dispose:x},qb=function(){function a(a){this.isSingle=a,this.isDisposed=!1,this.current=null}var b=a.prototype;return b.getDisposable=function(){return this.current},b.setDisposable=function(a){if(this.current&&this.isSingle)throw new Error("Disposable has already been assigned");var b,c=this.isDisposed;c||(b=this.current,this.current=a),b&&b.dispose(),c&&a&&a.dispose()},b.dispose=function(){var a;this.isDisposed||(this.isDisposed=!0,a=this.current,this.current=null),a&&a.dispose()},a}(),rb=w.SingleAssignmentDisposable=function(a){function b(){a.call(this,!0)}return fb(b,a),b}(qb),sb=w.SerialDisposable=function(a){function b(){a.call(this,!1)}return fb(b,a),b}(qb),tb=w.RefCountDisposable=function(){function a(a){this.disposable=a,this.disposable.count++,this.isInnerDisposed=!1}function b(a){this.underlyingDisposable=a,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return a.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},b.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},b.prototype.getDisposable=function(){return this.isDisposed?pb:new a(this)},b}();m.prototype.dispose=function(){var a=this;this.scheduler.schedule(function(){a.isDisposed||(a.isDisposed=!0,a.disposable.dispose())})};var ub=w.internals.ScheduledItem=function(a,b,c,d,e){this.scheduler=a,this.state=b,this.action=c,this.dueTime=d,this.comparer=e||B,this.disposable=new rb};ub.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ub.prototype.compareTo=function(a){return this.comparer(this.dueTime,a.dueTime)},ub.prototype.isCancelled=function(){return this.disposable.isDisposed},ub.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var vb,wb=w.Scheduler=function(){function a(a,b,c,d){this.now=a,this._schedule=b,this._scheduleRelative=c,this._scheduleAbsolute=d}function b(a,b){var c=b.first,d=b.second,e=new lb,f=function(b){d(b,function(b){var c=!1,d=!1,g=a.scheduleWithState(b,function(a,b){return c?e.remove(g):d=!0,f(b),pb});d||(e.add(g),c=!0)})};return f(c),e}function c(a,b,c){var d=b.first,e=b.second,f=new lb,g=function(b){e(b,function(b,d){var e=!1,h=!1,i=a[c].call(a,b,d,function(a,b){return e?f.remove(i):h=!0,g(b),pb});h||(f.add(i),e=!0)})};return g(d),f}function d(a,b){return b(),pb}var e=a.prototype;return e.catchException=e["catch"]=function(a){return new Bb(this,a)},e.schedulePeriodic=function(a,b){return this.schedulePeriodicWithState(null,a,function(){b()})},e.schedulePeriodicWithState=function(a,b,c){var d=a,e=setInterval(function(){d=c(d)},b);return ob(function(){clearInterval(e)})},e.schedule=function(a){return this._schedule(a,d)},e.scheduleWithState=function(a,b){return this._schedule(a,b)},e.scheduleWithRelative=function(a,b){return this._scheduleRelative(b,a,d)},e.scheduleWithRelativeAndState=function(a,b,c){return this._scheduleRelative(a,b,c)},e.scheduleWithAbsolute=function(a,b){return this._scheduleAbsolute(b,a,d)},e.scheduleWithAbsoluteAndState=function(a,b,c){return this._scheduleAbsolute(a,b,c)},e.scheduleRecursive=function(a){return this.scheduleRecursiveWithState(a,function(a,b){a(function(){b(a)})})},e.scheduleRecursiveWithState=function(a,c){return this.scheduleWithState({first:a,second:c},function(a,c){return b(a,c)})},e.scheduleRecursiveWithRelative=function(a,b){return this.scheduleRecursiveWithRelativeAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithRelativeAndState=function(a,b,d){return this._scheduleRelative({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithRelativeAndState")})},e.scheduleRecursiveWithAbsolute=function(a,b){return this.scheduleRecursiveWithAbsoluteAndState(b,a,function(a,b){a(function(c){b(a,c)})})},e.scheduleRecursiveWithAbsoluteAndState=function(a,b,d){return this._scheduleAbsolute({first:a,second:d},b,function(a,b){return c(a,b,"scheduleWithAbsoluteAndState")})},a.now=z,a.normalize=function(a){return 0>a&&(a=0),a},a}(),xb=wb.normalize,yb=(w.internals.SchedulePeriodicRecursive=function(){function a(a,b){b(0,this._period);try{this._state=this._action(this._state)}catch(c){throw this._cancel.dispose(),c}}function b(a,b,c,d){this._scheduler=a,this._state=b,this._period=c,this._action=d}return b.prototype.start=function(){var b=new rb;return this._cancel=b,b.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,a.bind(this))),b},b}(),wb.immediate=function(){function a(a,b){return b(this,a)}function b(a,b,c){for(var d=xb(d);d-this.now()>0;);return c(this,a)}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new wb(z,a,b,c)}()),zb=wb.currentThread=function(){function a(a){for(var b;a.length>0;)if(b=a.dequeue(),!b.isCancelled()){for(;b.dueTime-wb.now()>0;);b.isCancelled()||b.invoke()}}function b(a,b){return this.scheduleWithRelativeAndState(a,0,b)}function c(b,c,d){var f=this.now()+wb.normalize(c),g=new ub(this,b,d,f);if(e)e.enqueue(g);else{e=new jb(4),e.enqueue(g);try{a(e)}catch(h){throw h}finally{e=null}}return g.disposable}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var e,f=new wb(z,b,c,d);return f.scheduleRequired=function(){return null===e},f.ensureTrampoline=function(a){return null===e?this.schedule(a):a()},f}(),Ab=x;!function(){function a(){if(!r.postMessage||r.importScripts)return!1;var a=!1,b=r.onmessage;return r.onmessage=function(){a=!0},r.postMessage("","*"),r.onmessage=b,a}function b(a){if("string"==typeof a.data&&a.data.substring(0,f.length)===f){var b=a.data.substring(f.length),c=g[b];c(),delete g[b]}}var c=RegExp("^"+String(V).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),d="function"==typeof(d=v&&u&&v.setImmediate)&&!c.test(d)&&d,e="function"==typeof(e=v&&u&&v.clearImmediate)&&!c.test(e)&&e;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))vb=process.nextTick;else if("function"==typeof d)vb=d,Ab=e;else if(a()){var f="ms.rx.schedule"+Math.random(),g={},h=0;r.addEventListener?r.addEventListener("message",b,!1):r.attachEvent("onmessage",b,!1),vb=function(a){var b=h++;g[b]=a,r.postMessage(f+b,"*")}}else if(r.MessageChannel){var i=new r.MessageChannel,j={},k=0;i.port1.onmessage=function(a){var b=a.data,c=j[b];c(),delete j[b]},vb=function(a){var b=k++;j[b]=a,i.port2.postMessage(b)}}else"document"in r&&"onreadystatechange"in r.document.createElement("script")?vb=function(a){var b=r.document.createElement("script");b.onreadystatechange=function(){a(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},r.document.documentElement.appendChild(b)}:(vb=function(a){return setTimeout(a,0)},Ab=clearTimeout)}();var Bb=(wb.timeout=function(){function a(a,b){var c=this,d=new rb,e=vb(function(){d.isDisposed||d.setDisposable(b(c,a))});return new lb(d,ob(function(){Ab(e)}))}function b(a,b,c){var d=this,e=wb.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f=new rb,g=setTimeout(function(){f.isDisposed||f.setDisposable(c(d,a))},e);return new lb(f,ob(function(){clearTimeout(g)}))}function c(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new wb(z,a,b,c)}(),function(a){function b(){return this._scheduler.now()}function c(a,b){return this._scheduler.scheduleWithState(a,this._wrap(b))}function d(a,b,c){return this._scheduler.scheduleWithRelativeAndState(a,b,this._wrap(c))}function e(a,b,c){return this._scheduler.scheduleWithAbsoluteAndState(a,b,this._wrap(c))}function f(f,g){this._scheduler=f,this._handler=g,this._recursiveOriginal=null,this._recursiveWrapper=null,a.call(this,b,c,d,e)}return fb(f,a),f.prototype._clone=function(a){return new f(a,this._handler)},f.prototype._wrap=function(a){var b=this;return function(c,d){try{return a(b._getRecursiveWrapper(c),d)}catch(e){if(!b._handler(e))throw e;return pb}}},f.prototype._getRecursiveWrapper=function(a){if(this._recursiveOriginal!==a){this._recursiveOriginal=a;var b=this._clone(a);b._recursiveOriginal=a,b._recursiveWrapper=b,this._recursiveWrapper=b}return this._recursiveWrapper},f.prototype.schedulePeriodicWithState=function(a,b,c){var d=this,e=!1,f=new rb;return f.setDisposable(this._scheduler.schedulePeriodicWithState(a,b,function(a){if(e)return null;try{return c(a)}catch(b){if(e=!0,!d._handler(b))throw b;return f.dispose(),null}})),f},f}(wb)),Cb=w.Notification=function(){function a(a,b){this.hasValue=null==b?!1:b,this.kind=a}var b=a.prototype;return b.accept=function(a,b,c){return 1===arguments.length&&"object"==typeof a?this._acceptObservable(a):this._accept(a,b,c)},b.toObservable=function(a){var b=this;return a||(a=yb),new cc(function(c){return a.schedule(function(){b._acceptObservable(c),"N"===b.kind&&c.onCompleted()})})},a}(),Db=Cb.createOnNext=function(){function a(a){return a(this.value)}function b(a){return a.onNext(this.value)}function c(){return"OnNext("+this.value+")"}return function(d){var e=new Cb("N",!0);return e.value=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Eb=Cb.createOnError=function(){function a(a,b){return b(this.exception)}function b(a){return a.onError(this.exception)}function c(){return"OnError("+this.exception+")"}return function(d){var e=new Cb("E");return e.exception=d,e._accept=a,e._acceptObservable=b,e.toString=c,e}}(),Fb=Cb.createOnCompleted=function(){function a(a,b,c){return c()}function b(a){return a.onCompleted()}function c(){return"OnCompleted()"}return function(){var d=new Cb("C");return d._accept=a,d._acceptObservable=b,d.toString=c,d}}(),Gb=w.internals.Enumerator=function(a){this._next=a};Gb.prototype.next=function(){return this._next()},Gb.prototype[I]=function(){return this};var Hb=w.internals.Enumerable=function(a){this._iterator=a};Hb.prototype[I]=function(){return this._iterator()},Hb.prototype.concat=function(){var a=this;return new cc(function(b){var c;try{c=a[I]()}catch(d){return b.onError(),void 0}var e,f=new sb,g=yb.scheduleRecursive(function(a){var d;if(!e){try{d=c.next()}catch(g){return b.onError(g),void 0}if(d.done)return b.onCompleted(),void 0;var h=d.value;E(h)&&(h=Tb(h));var i=new rb;f.setDisposable(i),i.setDisposable(h.subscribe(b.onNext.bind(b),b.onError.bind(b),function(){a()}))}});return new lb(f,g,ob(function(){e=!0}))})},Hb.prototype.catchException=function(){var a=this;return new cc(function(b){var c;try{c=a[I]()}catch(d){return b.onError(),void 0}var e,f,g=new sb,h=yb.scheduleRecursive(function(a){if(!e){var d;try{d=c.next()}catch(h){return b.onError(h),void 0}if(d.done)return f?b.onError(f):b.onCompleted(),void 0;var i=d.value;E(i)&&(i=Tb(i));var j=new rb;g.setDisposable(j),j.setDisposable(i.subscribe(b.onNext.bind(b),function(b){f=b,a()},b.onCompleted.bind(b)))}});return new lb(g,h,ob(function(){e=!0}))})};var Ib=Hb.repeat=function(a,b){return null==b&&(b=-1),new Hb(function(){var c=b;return new Gb(function(){return 0===c?K:(c>0&&c--,{done:!1,value:a})})})},Jb=Hb.forEach=function(a,b,c){return b||(b=y),new Hb(function(){var d=-1;return new Gb(function(){return++d0&&(a=!this.isAcquired,this.isAcquired=!0),a&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(a){var c;if(!(b.queue.length>0))return b.isAcquired=!1,void 0;c=b.queue.shift();try{c()}catch(d){throw b.queue=[],b.hasFaulted=!0,d}a()}))},b.prototype.dispose=function(){a.prototype.dispose.call(this),this.disposable.dispose()},b}(Nb),Rb=function(a){function b(){a.apply(this,arguments)}return fb(b,a),b.prototype.next=function(b){a.prototype.next.call(this,b),this.ensureActive()},b.prototype.error=function(b){a.prototype.error.call(this,b),this.ensureActive()},b.prototype.completed=function(){a.prototype.completed.call(this),this.ensureActive()},b}(Qb),Sb=w.Observable=function(){function a(a){this._subscribe=a}return Mb=a.prototype,Mb.finalValue=function(){var a=this;return new cc(function(b){var c,d=!1;return a.subscribe(function(a){d=!0,c=a},b.onError.bind(b),function(){d?(b.onNext(c),b.onCompleted()):b.onError(new Error(F))})})},Mb.subscribe=Mb.forEach=function(a,b,c){var d;return d="object"==typeof a?a:Lb(a,b,c),this._subscribe(d)},Mb.toArray=function(){function a(a,b){var c=a.slice(0);return c.push(b),c}return this.scan([],a).startWith([]).finalValue()},a}();Mb.observeOn=function(a){var b=this;return new cc(function(c){return b.subscribe(new Rb(a,c))})},Mb.subscribeOn=function(a){var b=this;return new cc(function(c){var d=new rb,e=new sb;return e.setDisposable(d),d.setDisposable(a.schedule(function(){e.setDisposable(new m(a,b.subscribe(c)))})),e})};var Tb=Sb.fromPromise=function(a){return new cc(function(b){return a.then(function(a){b.onNext(a),b.onCompleted()},function(a){b.onError(a)}),function(){a&&a.abort&&a.abort()}})};Mb.toPromise=function(a){if(a||(a=w.config.Promise),!a)throw new Error("Promise type not provided nor in Rx.config.Promise");var b=this;return new a(function(a,c){var d,e=!1;b.subscribe(function(a){d=a,e=!0},function(a){c(a)},function(){e&&a(d)})})},Sb.create=Sb.createWithDisposable=function(a){return new cc(a)};var Ub=(Sb.defer=function(a){return new cc(function(b){var c;try{c=a()}catch(d){return Yb(d).subscribe(b)}return E(c)&&(c=Tb(c)),c.subscribe(b)})},Sb.empty=function(a){return a||(a=yb),new cc(function(b){return a.schedule(function(){b.onCompleted()})})}),Vb=Sb.fromArray=function(a,b){return b||(b=zb),new cc(function(c){var d=0;return b.scheduleRecursive(function(b){dc?(d.onNext(a+c),e(c+1)):d.onCompleted()})})},Sb.repeat=function(a,b,c){return c||(c=zb),null==b&&(b=-1),Xb(a,c).repeat(b)};var Xb=Sb["return"]=Sb.returnValue=function(a,b){return b||(b=yb),new cc(function(c){return b.schedule(function(){c.onNext(a),c.onCompleted()})})},Yb=Sb["throw"]=Sb.throwException=function(a,b){return b||(b=yb),new cc(function(c){return b.schedule(function(){c.onError(a)})})};Sb.using=function(a,b){return new cc(function(c){var d,e,f=pb;try{d=a(),d&&(f=d),e=b(d)}catch(g){return new lb(Yb(g).subscribe(c),f)}return new lb(e.subscribe(c),f)})},Mb.amb=function(a){var b=this;return new cc(function(c){function d(){f||(f=g,j.dispose())}function e(){f||(f=h,i.dispose())}var f,g="L",h="R",i=new rb,j=new rb;return E(a)&&(a=Tb(a)),i.setDisposable(b.subscribe(function(a){d(),f===g&&c.onNext(a)},function(a){d(),f===g&&c.onError(a)},function(){d(),f===g&&c.onCompleted()})),j.setDisposable(a.subscribe(function(a){e(),f===h&&c.onNext(a)},function(a){e(),f===h&&c.onError(a)},function(){e(),f===h&&c.onCompleted()})),new lb(i,j)})},Sb.amb=function(){function a(a,b){return a.amb(b)}for(var b=Wb(),c=k(arguments,0),d=0,e=c.length;e>d;d++)b=a(b,c[d]);return b},Mb["catch"]=Mb.catchException=function(a){return"function"==typeof a?n(this,a):Zb([this,a])};var Zb=Sb.catchException=Sb["catch"]=function(){var a=k(arguments,0);return Jb(a).catchException()};Mb.combineLatest=function(){var a=eb.call(arguments);return Array.isArray(a[0])?a[0].unshift(this):a.unshift(this),$b.apply(this,a)};var $b=Sb.combineLatest=function(){var a=eb.call(arguments),b=a.pop();return Array.isArray(a[0])&&(a=a[0]),new cc(function(c){function d(a){var d;if(h[a]=!0,i||(i=h.every(y))){try{d=b.apply(null,k)}catch(e){return c.onError(e),void 0}c.onNext(d)}else j.filter(function(b,c){return c!==a}).every(y)&&c.onCompleted()}function e(a){j[a]=!0,j.every(y)&&c.onCompleted()}for(var f=function(){return!1},g=a.length,h=l(g,f),i=!1,j=l(g,f),k=new Array(g),m=new Array(g),n=0;g>n;n++)!function(b){var f=a[b],g=new rb;E(f)&&(f=Tb(f)),g.setDisposable(f.subscribe(function(a){k[b]=a,d(b)},c.onError.bind(c),function(){e(b)})),m[b]=g}(n);return new lb(m)})};Mb.concat=function(){var a=eb.call(arguments,0);return a.unshift(this),_b.apply(this,a)};var _b=Sb.concat=function(){var a=k(arguments,0);return Jb(a).concat()};Mb.concatObservable=Mb.concatAll=function(){return this.merge(1)},Mb.merge=function(a){if("number"!=typeof a)return ac(this,a);var b=this;return new cc(function(c){var d=0,e=new lb,f=!1,g=[],h=function(a){var b=new rb;e.add(b),E(a)&&(a=Tb(a)),b.setDisposable(a.subscribe(c.onNext.bind(c),c.onError.bind(c),function(){var a;e.remove(b),g.length>0?(a=g.shift(),h(a)):(d--,f&&0===d&&c.onCompleted())}))};return e.add(b.subscribe(function(b){a>d?(d++,h(b)):g.push(b)},c.onError.bind(c),function(){f=!0,0===d&&c.onCompleted()})),e})};var ac=Sb.merge=function(){var a,b;return arguments[0]?arguments[0].now?(a=arguments[0],b=eb.call(arguments,1)):(a=yb,b=eb.call(arguments,0)):(a=yb,b=eb.call(arguments,1)),Array.isArray(b[0])&&(b=b[0]),Vb(b,a).mergeObservable()};Mb.mergeObservable=Mb.mergeAll=function(){var a=this;return new cc(function(b){var c=new lb,d=!1,e=new rb;return c.add(e),e.setDisposable(a.subscribe(function(a){var e=new rb;c.add(e),E(a)&&(a=Tb(a)),e.setDisposable(a.subscribe(function(a){b.onNext(a)},b.onError.bind(b),function(){c.remove(e),d&&1===c.length&&b.onCompleted()}))},b.onError.bind(b),function(){d=!0,1===c.length&&b.onCompleted()})),c})},Mb.onErrorResumeNext=function(a){if(!a)throw new Error("Second observable is required");return bc([this,a])};var bc=Sb.onErrorResumeNext=function(){var a=k(arguments,0);return new cc(function(b){var c=0,d=new sb,e=yb.scheduleRecursive(function(e){var f,g;c0})){try{f=h.map(function(a){return a.shift()}),e=c.apply(a,f)}catch(g){return d.onError(g),void 0}d.onNext(e)}else i.filter(function(a,c){return c!==b}).every(y)&&d.onCompleted()}function f(a){i[a]=!0,i.every(function(a){return a})&&d.onCompleted()}for(var g=b.length,h=l(g,function(){return[]}),i=l(g,function(){return!1}),j=new Array(g),k=0;g>k;k++)!function(a){var c=b[a],g=new rb;E(c)&&(c=Tb(c)),g.setDisposable(c.subscribe(function(b){h[a].push(b),e(a)},d.onError.bind(d),function(){f(a)})),j[a]=g}(k);return new lb(j)})},Sb.zip=function(){var a=eb.call(arguments,0),b=a.shift();return b.zip.apply(b,a)},Sb.zipArray=function(){var a=k(arguments,0);return new cc(function(b){function c(a){if(f.every(function(a){return a.length>0})){var c=f.map(function(a){return a.shift()});b.onNext(c)}else if(g.filter(function(b,c){return c!==a}).every(y))return b.onCompleted(),void 0}function d(a){return g[a]=!0,g.every(y)?(b.onCompleted(),void 0):void 0}for(var e=a.length,f=l(e,function(){return[]}),g=l(e,function(){return!1}),h=new Array(e),i=0;e>i;i++)!function(e){h[e]=new rb,h[e].setDisposable(a[e].subscribe(function(a){f[e].push(a),c(e)},b.onError.bind(b),function(){d(e)}))}(i);var j=new lb(h);return j.add(ob(function(){for(var a=0,b=f.length;b>a;a++)f[a]=[]})),j})},Mb.asObservable=function(){var a=this;return new cc(function(b){return a.subscribe(b)})},Mb.bufferWithCount=function(a,b){return 1===arguments.length&&(b=a),this.windowWithCount(a,b).selectMany(function(a){return a.toArray()}).where(function(a){return a.length>0})},Mb.dematerialize=function(){var a=this;return new cc(function(b){return a.subscribe(function(a){return a.accept(b)},b.onError.bind(b),b.onCompleted.bind(b))})},Mb.distinctUntilChanged=function(a,b){var c=this;return a||(a=y),b||(b=A),new cc(function(d){var e,f=!1;return c.subscribe(function(c){var g,h=!1;try{g=a(c)}catch(i){return d.onError(i),void 0}if(f)try{h=b(e,g)}catch(i){return d.onError(i),void 0}f&&h||(f=!0,e=g,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Mb["do"]=Mb.doAction=function(a,b,c){var d,e=this;return"function"==typeof a?d=a:(d=a.onNext.bind(a),b=a.onError.bind(a),c=a.onCompleted.bind(a)),new cc(function(a){return e.subscribe(function(b){try{d(b) +}catch(c){a.onError(c)}a.onNext(b)},function(c){if(b){try{b(c)}catch(d){a.onError(d)}a.onError(c)}else a.onError(c)},function(){if(c){try{c()}catch(b){a.onError(b)}a.onCompleted()}else a.onCompleted()})})},Mb["finally"]=Mb.finallyAction=function(a){var b=this;return new cc(function(c){var d=b.subscribe(c);return ob(function(){try{d.dispose()}catch(b){throw b}finally{a()}})})},Mb.ignoreElements=function(){var a=this;return new cc(function(b){return a.subscribe(x,b.onError.bind(b),b.onCompleted.bind(b))})},Mb.materialize=function(){var a=this;return new cc(function(b){return a.subscribe(function(a){b.onNext(Db(a))},function(a){b.onNext(Eb(a)),b.onCompleted()},function(){b.onNext(Fb()),b.onCompleted()})})},Mb.repeat=function(a){return Ib(this,a).concat()},Mb.retry=function(a){return Ib(this,a).catchException()},Mb.scan=function(){var a,b,c=!1,d=this;return 2===arguments.length?(c=!0,a=arguments[0],b=arguments[1]):b=arguments[0],new cc(function(e){var f,g,h;return d.subscribe(function(d){try{h||(h=!0),f?g=b(g,d):(g=c?b(a,d):d,f=!0)}catch(i){return e.onError(i),void 0}e.onNext(g)},e.onError.bind(e),function(){!h&&c&&e.onNext(a),e.onCompleted()})})},Mb.skipLast=function(a){var b=this;return new cc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&c.onNext(d.shift())},c.onError.bind(c),c.onCompleted.bind(c))})},Mb.startWith=function(){var a,b,c=0;return arguments.length&&"now"in Object(arguments[0])?(b=arguments[0],c=1):b=yb,a=eb.call(arguments,c),Jb([Vb(a,b),this]).concat()},Mb.takeLast=function(a,b){return this.takeLastBuffer(a).selectMany(function(a){return Vb(a,b)})},Mb.takeLastBuffer=function(a){var b=this;return new cc(function(c){var d=[];return b.subscribe(function(b){d.push(b),d.length>a&&d.shift()},c.onError.bind(c),function(){c.onNext(d),c.onCompleted()})})},Mb.windowWithCount=function(a,b){var c=this;if(0>=a)throw new Error(G);if(1===arguments.length&&(b=a),0>=b)throw new Error(G);return new cc(function(d){var e=new rb,f=new tb(e),g=0,h=[],i=function(){var a=new gc;h.push(a),d.onNext(hb(a,f))};return i(),e.setDisposable(c.subscribe(function(c){for(var d,e=0,f=h.length;f>e;e++)h[e].onNext(c);var j=g-a+1;j>=0&&j%b===0&&(d=h.shift(),d.onCompleted()),g++,g%b===0&&i()},function(a){for(;h.length>0;)h.shift().onError(a);d.onError(a)},function(){for(;h.length>0;)h.shift().onCompleted();d.onCompleted()})),f})},Mb.defaultIfEmpty=function(b){var c=this;return b===a&&(b=null),new cc(function(a){var d=!1;return c.subscribe(function(b){d=!0,a.onNext(b)},a.onError.bind(a),function(){d||a.onNext(b),a.onCompleted()})})},Mb.distinct=function(a,b){var c=this;return a||(a=y),b||(b=C),new cc(function(d){var e={};return c.subscribe(function(c){var f,g,h,i=!1;try{f=a(c),g=b(f)}catch(j){return d.onError(j),void 0}for(h in e)if(g===h){i=!0;break}i||(e[g]=null,d.onNext(c))},d.onError.bind(d),d.onCompleted.bind(d))})},Mb.groupBy=function(a,b,c){return this.groupByUntil(a,b,function(){return Wb()},c)},Mb.groupByUntil=function(a,b,c,d){var e=this;return b||(b=y),d||(d=C),new cc(function(f){var g={},h=new lb,i=new tb(h);return h.add(e.subscribe(function(e){var j,k,l,m,n,o,p,q,r,s;try{o=a(e),p=d(o)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}m=!1;try{r=g[p],r||(r=new gc,g[p]=r,m=!0)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}if(m){n=new ec(o,r,i),k=new ec(o,r);try{j=c(k)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}f.onNext(n),q=new rb,h.add(q);var u=function(){p in g&&(delete g[p],r.onCompleted()),h.remove(q)};q.setDisposable(j.take(1).subscribe(x,function(a){for(s in g)g[s].onError(a);f.onError(a)},function(){u()}))}try{l=b(e)}catch(t){for(s in g)g[s].onError(t);return f.onError(t),void 0}r.onNext(l)},function(a){for(var b in g)g[b].onError(a);f.onError(a)},function(){for(var a in g)g[a].onCompleted();f.onCompleted()})),i})},Mb.select=Mb.map=function(a,b){var c=this;return new cc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Mb.pluck=function(a){return this.select(function(b){return b[a]})},Mb.selectMany=Mb.flatMap=function(a,b){return b?this.selectMany(function(c,d){var e=a(c,d),f=E(e)?Tb(e):e;return f.select(function(a){return b(c,a,d)})}):"function"==typeof a?p.call(this,a):p.call(this,function(){return a})},Mb.selectSwitch=Mb.flatMapLatest=function(a,b){return this.select(a,b).switchLatest()},Mb.skip=function(a){if(0>a)throw new Error(G);var b=this;return new cc(function(c){var d=a;return b.subscribe(function(a){0>=d?c.onNext(a):d--},c.onError.bind(c),c.onCompleted.bind(c))})},Mb.skipWhile=function(a,b){var c=this;return new cc(function(d){var e=0,f=!1;return c.subscribe(function(g){if(!f)try{f=!a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f&&d.onNext(g)},d.onError.bind(d),d.onCompleted.bind(d))})},Mb.take=function(a,b){if(0>a)throw new Error(G);if(0===a)return Ub(b);var c=this;return new cc(function(b){var d=a;return c.subscribe(function(a){d>0&&(d--,b.onNext(a),0===d&&b.onCompleted())},b.onError.bind(b),b.onCompleted.bind(b))})},Mb.takeWhile=function(a,b){var c=this;return new cc(function(d){var e=0,f=!0;return c.subscribe(function(g){if(f){try{f=a.call(b,g,e++,c)}catch(h){return d.onError(h),void 0}f?d.onNext(g):d.onCompleted()}},d.onError.bind(d),d.onCompleted.bind(d))})},Mb.where=Mb.filter=function(a,b){var c=this;return new cc(function(d){var e=0;return c.subscribe(function(f){var g;try{g=a.call(b,f,e++,c)}catch(h){return d.onError(h),void 0}g&&d.onNext(f)},d.onError.bind(d),d.onCompleted.bind(d))})};var cc=w.AnonymousObservable=function(a){function b(a){return"undefined"==typeof a?a=pb:"function"==typeof a&&(a=ob(a)),a}function c(d){function e(a){var c=new dc(a);if(zb.scheduleRequired())zb.schedule(function(){try{c.setDisposable(b(d(c)))}catch(a){if(!c.fail(a))throw a}});else try{c.setDisposable(b(d(c)))}catch(e){if(!c.fail(e))throw e}return c}return this instanceof c?(a.call(this,e),void 0):new c(d)}return fb(c,a),c}(Sb),dc=function(a){function b(b){a.call(this),this.observer=b,this.m=new rb}fb(b,a);var c=b.prototype;return c.next=function(a){var b=!1;try{this.observer.onNext(a),b=!0}catch(c){throw c}finally{b||this.dispose()}},c.error=function(a){try{this.observer.onError(a)}catch(b){throw b}finally{this.dispose()}},c.completed=function(){try{this.observer.onCompleted()}catch(a){throw a}finally{this.dispose()}},c.setDisposable=function(a){this.m.setDisposable(a)},c.getDisposable=function(){return this.m.getDisposable()},c.disposable=function(a){return arguments.length?this.getDisposable():setDisposable(a)},c.dispose=function(){a.prototype.dispose.call(this),this.m.dispose()},b}(Nb),ec=function(a){function b(a){return this.underlyingObservable.subscribe(a)}function c(c,d,e){a.call(this,b),this.key=c,this.underlyingObservable=e?new cc(function(a){return new lb(e.getDisposable(),d.subscribe(a))}):d}return fb(c,a),c}(Sb),fc=function(a,b){this.subject=a,this.observer=b};fc.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var a=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(a,1),this.observer=null}};var gc=w.Subject=function(a){function c(a){return b.call(this),this.isStopped?this.exception?(a.onError(this.exception),pb):(a.onCompleted(),pb):(this.observers.push(a),new fc(this,a))}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return fb(d,a),gb(d.prototype,Kb,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(b.call(this),!this.isStopped){var a=this.observers.slice(0);this.isStopped=!0;for(var c=0,d=a.length;d>c;c++)a[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){if(b.call(this),!this.isStopped)for(var c=this.observers.slice(0),d=0,e=c.length;e>d;d++)c[d].onNext(a)},dispose:function(){this.isDisposed=!0,this.observers=null}}),d.create=function(a,b){return new hc(a,b)},d}(Sb),hc=(w.AsyncSubject=function(a){function c(a){if(b.call(this),!this.isStopped)return this.observers.push(a),new fc(this,a);var c=this.exception,d=this.hasValue,e=this.value;return c?a.onError(c):d?(a.onNext(e),a.onCompleted()):a.onCompleted(),pb}function d(){a.call(this,c),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return fb(d,a),gb(d.prototype,Kb,{hasObservers:function(){return b.call(this),this.observers.length>0},onCompleted:function(){var a,c,d;if(b.call(this),!this.isStopped){this.isStopped=!0;var e=this.observers.slice(0),f=this.value,g=this.hasValue;if(g)for(c=0,d=e.length;d>c;c++)a=e[c],a.onNext(f),a.onCompleted();else for(c=0,d=e.length;d>c;c++)e[c].onCompleted();this.observers=[]}},onError:function(a){if(b.call(this),!this.isStopped){var c=this.observers.slice(0);this.isStopped=!0,this.exception=a;for(var d=0,e=c.length;e>d;d++)c[d].onError(a);this.observers=[]}},onNext:function(a){b.call(this),this.isStopped||(this.value=a,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),d}(Sb),function(a){function b(a){return this.observable.subscribe(a)}function c(c,d){a.call(this,b),this.observer=c,this.observable=d}return fb(c,a),gb(c.prototype,Kb,{onCompleted:function(){this.observer.onCompleted()},onError:function(a){this.observer.onError(a)},onNext:function(a){this.observer.onNext(a)}}),c}(Sb));"function"==typeof define&&"object"==typeof define.amd&&define.amd?(r.Rx=w,define(function(){return w})):s&&t?u?(t.exports=w).Rx=w:s.Rx=w:r.Rx=w}).call(this); \ No newline at end of file diff --git a/js/libs/rxjs/rx.node.js b/js/libs/rxjs/rx.node.js new file mode 100644 index 0000000..96116cd --- /dev/null +++ b/js/libs/rxjs/rx.node.js @@ -0,0 +1,144 @@ +var Rx = require('./rx'); +require('./rx.aggregates'); +require('./rx.backpressure'); +require('./rx.async'); +require('./rx.binding'); +require('./rx.coincidence'); +require('./rx.experimental'); +require('./rx.joinpatterns'); +require('./rx.time'); +require('./rx.virtualtime'); +require('./rx.testing'); + +// Add specific Node functions +var EventEmitter = require('events').EventEmitter, + Observable = Rx.Observable; + +Rx.Node = { + /** + * @deprecated Use Rx.Observable.fromCallback from rx.async.js instead. + * + * Converts a callback function to an observable sequence. + * + * @param {Function} func Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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 event handler to produce a single item to yield on next. + * @returns {Function} Asynchronous function. + */ + fromCallback: function (func, scheduler, context, selector) { + return Observable.fromCallback(func, scheduler, context, selector); + }, + + /** + * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. + * + * 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 {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @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 event handler 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. + */ + fromNodeCallback: function (func, scheduler, context, selector) { + return Observable.fromNodeCallback(func, scheduler, context, selector); + }, + + /** + * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. + * + * Handles an event from the given EventEmitter as an observable sequence. + * + * @param {EventEmitter} eventEmitter The EventEmitter to subscribe to the given event. + * @param {String} eventName The event name to subscribe + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence generated from the named event from the given EventEmitter. The data will be returned as an array of arguments to the handler. + */ + fromEvent: function (eventEmitter, eventName, selector) { + return Observable.fromEvent(eventEmitter, eventName, selector); + }, + + /** + * Converts the given observable sequence to an event emitter with the given event name. + * The errors are handled on the 'error' event and completion on the 'end' event. + * @param {Observable} observable The observable sequence to convert to an EventEmitter. + * @param {String} eventName The event name to emit onNext calls. + * @returns {EventEmitter} An EventEmitter which emits the given eventName for each onNext call in addition to 'error' and 'end' events. + * You must call publish in order to invoke the subscription on the Observable sequuence. + */ + toEventEmitter: function (observable, eventName) { + var e = new EventEmitter(); + + // Used to publish the events from the observable + e.publish = function () { + e.subscription = observable.subscribe( + function (x) { + e.emit(eventName, x); + }, + function (err) { + e.emit('error', err); + }, + function () { + e.emit('end'); + }); + }; + + return e; + }, + + /** + * Converts a flowing stream to an Observable sequence. + * @param {Stream} stream A stream to convert to a observable sequence. + * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'end' events. + */ + fromStream: function (stream) { + return Observable.create(function (observer) { + function dataHandler (data) { + observer.onNext(data); + } + + function errorHandler (err) { + observer.onError(err); + } + + function endHandler () { + observer.onCompleted(); + } + + stream.addListener('data', dataHandler); + stream.addListener('error', errorHandler); + stream.addListener('end', endHandler); + + return function () { + stream.removeListener('data', dataHandler); + stream.removeListener('error', errorHandler); + stream.removeListener('end', endHandler); + }; + }).publish().refCount(); + }, + + /** + * Writes an observable sequence to a stream + * @param {Observable} observable Observable sequence to write to a stream. + * @param {Stream} stream The stream to write to. + * @param {String} [encoding] The encoding of the item to write. + * @returns {Disposable} The subscription handle. + */ + writeToStream: function (observable, stream, encoding) { + return observable.subscribe( + function (x) { + stream.write(String(x), encoding); + }, + function (err) { + stream.emit('error', err); + }, function () { + // Hack check because STDIO is not closable + if (!stream._isStdio) { + stream.end(); + } + }); + } +}; + +module.exports = Rx; \ No newline at end of file diff --git a/js/libs/rxjs/rx.testing.js b/js/libs/rxjs/rx.testing.js new file mode 100644 index 0000000..b13694d --- /dev/null +++ b/js/libs/rxjs/rx.testing.js @@ -0,0 +1,500 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx.virtualtime', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Defaults + var Observer = Rx.Observer, + Observable = Rx.Observable, + Notification = Rx.Notification, + VirtualTimeScheduler = Rx.VirtualTimeScheduler, + Disposable = Rx.Disposable, + disposableEmpty = Disposable.empty, + disposableCreate = Disposable.create, + CompositeDisposable = Rx.CompositeDisposable, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + slice = Array.prototype.slice, + inherits = Rx.internals.inherits, + defaultComparer = Rx.internals.isEqual; + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** + * @private + * @constructor + */ + function OnNextPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnNextPredicate# + */ + OnNextPredicate.prototype.equals = function (other) { + if (other === this) { return true; } + if (other == null) { return false; } + if (other.kind !== 'N') { return false; } + return this.predicate(other.value); + }; + + /** + * @private + * @constructor + */ + function OnErrorPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnErrorPredicate# + */ + OnErrorPredicate.prototype.equals = function (other) { + if (other === this) { return true; } + if (other == null) { return false; } + if (other.kind !== 'E') { return false; } + return this.predicate(other.exception); + }; + + /** + * @static + * type Object + */ + var ReactiveTest = Rx.ReactiveTest = { + /** Default virtual time used for creation of observable sequences in unit tests. */ + created: 100, + /** Default virtual time used to subscribe to observable sequences in unit tests. */ + subscribed: 200, + /** Default virtual time used to dispose subscriptions in unit tests. */ + disposed: 1000, + + /** + * Factory method for an OnNext notification record at a given time with a given value or a predicate function. + * + * 1 - ReactiveTest.onNext(200, 42); + * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; }); + * + * @param ticks Recorded virtual time the OnNext notification occurs. + * @param value Recorded value stored in the OnNext notification or a predicate. + * @return Recorded OnNext notification. + */ + onNext: function (ticks, value) { + if (typeof value === 'function') { + return new Recorded(ticks, new OnNextPredicate(value)); + } + return new Recorded(ticks, Notification.createOnNext(value)); + }, + /** + * Factory method for an OnError notification record at a given time with a given error. + * + * 1 - ReactiveTest.onNext(200, new Error('error')); + * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; }); + * + * @param ticks Recorded virtual time the OnError notification occurs. + * @param exception Recorded exception stored in the OnError notification. + * @return Recorded OnError notification. + */ + onError: function (ticks, exception) { + if (typeof exception === 'function') { + return new Recorded(ticks, new OnErrorPredicate(exception)); + } + return new Recorded(ticks, Notification.createOnError(exception)); + }, + /** + * Factory method for an OnCompleted notification record at a given time. + * + * @param ticks Recorded virtual time the OnCompleted notification occurs. + * @return Recorded OnCompleted notification. + */ + onCompleted: function (ticks) { + return new Recorded(ticks, Notification.createOnCompleted()); + }, + /** + * Factory method for a subscription record based on a given subscription and disposal time. + * + * @param start Virtual time indicating when the subscription was created. + * @param end Virtual time indicating when the subscription was disposed. + * @return Subscription object. + */ + subscribe: function (start, end) { + return new Subscription(start, end); + } + }; + + /** + * Creates a new object recording the production of the specified value at the given virtual time. + * + * @constructor + * @param {Number} time Virtual time the value was produced on. + * @param {Mixed} value Value that was produced. + * @param {Function} comparer An optional comparer. + */ + var Recorded = Rx.Recorded = function (time, value, comparer) { + this.time = time; + this.value = value; + this.comparer = comparer || defaultComparer; + }; + + /** + * Checks whether the given recorded object is equal to the current instance. + * + * @param {Recorded} other Recorded object to check for equality. + * @returns {Boolean} true if both objects are equal; false otherwise. + */ + Recorded.prototype.equals = function (other) { + return this.time === other.time && this.comparer(this.value, other.value); + }; + + /** + * Returns a string representation of the current Recorded value. + * + * @returns {String} String representation of the current Recorded value. + */ + Recorded.prototype.toString = function () { + return this.value.toString() + '@' + this.time; + }; + + /** + * Creates a new subscription object with the given virtual subscription and unsubscription time. + * + * @constructor + * @param {Number} subscribe Virtual time at which the subscription occurred. + * @param {Number} unsubscribe Virtual time at which the unsubscription occurred. + */ + var Subscription = Rx.Subscription = function (start, end) { + this.subscribe = start; + this.unsubscribe = end || Number.MAX_VALUE; + }; + + /** + * Checks whether the given subscription is equal to the current instance. + * @param other Subscription object to check for equality. + * @returns {Boolean} true if both objects are equal; false otherwise. + */ + Subscription.prototype.equals = function (other) { + return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe; + }; + + /** + * Returns a string representation of the current Subscription value. + * @returns {String} String representation of the current Subscription value. + */ + Subscription.prototype.toString = function () { + return '(' + this.subscribe + ', ' + this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe + ')'; + }; + + /** @private */ + var MockDisposable = Rx.MockDisposable = function (scheduler) { + this.scheduler = scheduler; + this.disposes = []; + this.disposes.push(this.scheduler.clock); + }; + + /* + * @memberOf MockDisposable# + * @prviate + */ + MockDisposable.prototype.dispose = function () { + this.disposes.push(this.scheduler.clock); + }; + + /** @private */ + var MockObserver = (function (_super) { + inherits(MockObserver, _super); + + /* + * @constructor + * @prviate + */ + function MockObserver(scheduler) { + _super.call(this); + this.scheduler = scheduler; + this.messages = []; + } + + var MockObserverPrototype = MockObserver.prototype; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onNext = function (value) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onError = function (exception) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onCompleted = function () { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); + }; + + return MockObserver; + })(Observer); + + /** @private */ + var HotObservable = (function (_super) { + + function subscribe(observer) { + var observable = this; + this.observers.push(observer); + this.subscriptions.push(new Subscription(this.scheduler.clock)); + var index = this.subscriptions.length - 1; + return disposableCreate(function () { + var idx = observable.observers.indexOf(observer); + observable.observers.splice(idx, 1); + observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); + }); + } + + inherits(HotObservable, _super); + + /** + * @private + * @constructor + */ + function HotObservable(scheduler, messages) { + _super.call(this, subscribe); + var message, notification, observable = this; + this.scheduler = scheduler; + this.messages = messages; + this.subscriptions = []; + this.observers = []; + for (var i = 0, len = this.messages.length; i < len; i++) { + message = this.messages[i]; + notification = message.value; + (function (innerNotification) { + scheduler.scheduleAbsoluteWithState(null, message.time, function () { + var obs = observable.observers.slice(0); + + for (var j = 0, jLen = obs.length; j < jLen; j++) { + innerNotification.accept(obs[j]); + } + return disposableEmpty; + }); + })(notification); + } + } + + return HotObservable; + })(Observable); + + /** @private */ + var ColdObservable = (function (_super) { + + function subscribe(observer) { + var message, notification, observable = this; + this.subscriptions.push(new Subscription(this.scheduler.clock)); + var index = this.subscriptions.length - 1; + var d = new CompositeDisposable(); + for (var i = 0, len = this.messages.length; i < len; i++) { + message = this.messages[i]; + notification = message.value; + (function (innerNotification) { + d.add(observable.scheduler.scheduleRelativeWithState(null, message.time, function () { + innerNotification.accept(observer); + return disposableEmpty; + })); + })(notification); + } + return disposableCreate(function () { + observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); + d.dispose(); + }); + } + + inherits(ColdObservable, _super); + + /** + * @private + * @constructor + */ + function ColdObservable(scheduler, messages) { + _super.call(this, subscribe); + this.scheduler = scheduler; + this.messages = messages; + this.subscriptions = []; + } + + return ColdObservable; + })(Observable); + + /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */ + Rx.TestScheduler = (function (_super) { + inherits(TestScheduler, _super); + + function baseComparer(x, y) { + return x > y ? 1 : (x < y ? -1 : 0); + } + + /** @constructor */ + function TestScheduler() { + _super.call(this, 0, baseComparer); + } + + /** + * Schedules an action to be executed at the specified virtual time. + * + * @param state State passed to the action to be executed. + * @param dueTime Absolute virtual time at which to execute the action. + * @param action Action to be executed. + * @return Disposable object used to cancel the scheduled action (best effort). + */ + TestScheduler.prototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + if (dueTime <= this.clock) { + dueTime = this.clock + 1; + } + return _super.prototype.scheduleAbsoluteWithState.call(this, state, dueTime, action); + }; + /** + * Adds a relative virtual time to an absolute virtual time value. + * + * @param absolute Absolute virtual time value. + * @param relative Relative virtual time value to add. + * @return Resulting absolute virtual time sum value. + */ + TestScheduler.prototype.add = function (absolute, relative) { + return absolute + relative; + }; + /** + * Converts the absolute virtual time value to a DateTimeOffset value. + * + * @param absolute Absolute virtual time value to convert. + * @return Corresponding DateTimeOffset value. + */ + TestScheduler.prototype.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + /** + * Converts the TimeSpan value to a relative virtual time value. + * + * @param timeSpan TimeSpan value to convert. + * @return Corresponding relative virtual time value. + */ + TestScheduler.prototype.toRelative = function (timeSpan) { + return timeSpan; + }; + /** + * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. + * + * @param create Factory method to create an observable sequence. + * @param created Virtual time at which to invoke the factory to create an observable sequence. + * @param subscribed Virtual time at which to subscribe to the created observable sequence. + * @param disposed Virtual time at which to dispose the subscription. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithTiming = function (create, created, subscribed, disposed) { + var observer = this.createObserver(), source, subscription; + this.scheduleAbsoluteWithState(null, created, function () { + source = create(); + return disposableEmpty; + }); + this.scheduleAbsoluteWithState(null, subscribed, function () { + subscription = source.subscribe(observer); + return disposableEmpty; + }); + this.scheduleAbsoluteWithState(null, disposed, function () { + subscription.dispose(); + return disposableEmpty; + }); + this.start(); + return observer; + }; + /** + * Starts the test scheduler and uses the specified virtual time to dispose the subscription to the sequence obtained through the factory function. + * Default virtual times are used for factory invocation and sequence subscription. + * + * @param create Factory method to create an observable sequence. + * @param disposed Virtual time at which to dispose the subscription. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithDispose = function (create, disposed) { + return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, disposed); + }; + /** + * Starts the test scheduler and uses default virtual times to invoke the factory function, to subscribe to the resulting sequence, and to dispose the subscription. + * + * @param create Factory method to create an observable sequence. + * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. + */ + TestScheduler.prototype.startWithCreate = function (create) { + return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, ReactiveTest.disposed); + }; + /** + * Creates a hot observable using the specified timestamped notification messages either as an array or arguments. + * + * @param messages Notifications to surface through the created sequence at their specified absolute virtual times. + * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications. + */ + TestScheduler.prototype.createHotObservable = function () { + var messages = argsOrArray(arguments, 0); + return new HotObservable(this, messages); + }; + /** + * Creates a cold observable using the specified timestamped notification messages either as an array or arguments. + * + * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. + * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications. + */ + TestScheduler.prototype.createColdObservable = function () { + var messages = argsOrArray(arguments, 0); + return new ColdObservable(this, messages); + }; + /** + * Creates an observer that records received notification messages and timestamps those. + * + * @return Observer that can be used to assert the timing of received notifications. + */ + TestScheduler.prototype.createObserver = function () { + return new MockObserver(this); + }; + + return TestScheduler; + })(VirtualTimeScheduler); + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.testing.min.js b/js/libs/rxjs/rx.testing.min.js new file mode 100644 index 0000000..05ed022 --- /dev/null +++ b/js/libs/rxjs/rx.testing.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx.virtualtime","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){function d(a,b){return 1===a.length&&Array.isArray(a[b])?a[b]:o.call(a)}function e(a){this.predicate=a}function f(a){this.predicate=a}var g=c.Observer,h=c.Observable,i=c.Notification,j=c.VirtualTimeScheduler,k=c.Disposable,l=k.empty,m=k.create,n=c.CompositeDisposable,o=(c.SingleAssignmentDisposable,Array.prototype.slice),p=c.internals.inherits,q=c.internals.isEqual;e.prototype.equals=function(a){return a===this?!0:null==a?!1:"N"!==a.kind?!1:this.predicate(a.value)},f.prototype.equals=function(a){return a===this?!0:null==a?!1:"E"!==a.kind?!1:this.predicate(a.exception)};var r=c.ReactiveTest={created:100,subscribed:200,disposed:1e3,onNext:function(a,b){return"function"==typeof b?new s(a,new e(b)):new s(a,i.createOnNext(b))},onError:function(a,b){return"function"==typeof b?new s(a,new f(b)):new s(a,i.createOnError(b))},onCompleted:function(a){return new s(a,i.createOnCompleted())},subscribe:function(a,b){return new t(a,b)}},s=c.Recorded=function(a,b,c){this.time=a,this.value=b,this.comparer=c||q};s.prototype.equals=function(a){return this.time===a.time&&this.comparer(this.value,a.value)},s.prototype.toString=function(){return this.value.toString()+"@"+this.time};var t=c.Subscription=function(a,b){this.subscribe=a,this.unsubscribe=b||Number.MAX_VALUE};t.prototype.equals=function(a){return this.subscribe===a.subscribe&&this.unsubscribe===a.unsubscribe},t.prototype.toString=function(){return"("+this.subscribe+", "+this.unsubscribe===Number.MAX_VALUE?"Infinite":this.unsubscribe+")"};var u=c.MockDisposable=function(a){this.scheduler=a,this.disposes=[],this.disposes.push(this.scheduler.clock)};u.prototype.dispose=function(){this.disposes.push(this.scheduler.clock)};var v=function(a){function b(b){a.call(this),this.scheduler=b,this.messages=[]}p(b,a);var c=b.prototype;return c.onNext=function(a){this.messages.push(new s(this.scheduler.clock,i.createOnNext(a)))},c.onError=function(a){this.messages.push(new s(this.scheduler.clock,i.createOnError(a)))},c.onCompleted=function(){this.messages.push(new s(this.scheduler.clock,i.createOnCompleted()))},b}(g),w=function(a){function b(a){var b=this;this.observers.push(a),this.subscriptions.push(new t(this.scheduler.clock));var c=this.subscriptions.length-1;return m(function(){var d=b.observers.indexOf(a);b.observers.splice(d,1),b.subscriptions[c]=new t(b.subscriptions[c].subscribe,b.scheduler.clock)})}function c(c,d){a.call(this,b);var e,f,g=this;this.scheduler=c,this.messages=d,this.subscriptions=[],this.observers=[];for(var h=0,i=this.messages.length;i>h;h++)e=this.messages[h],f=e.value,function(a){c.scheduleAbsoluteWithState(null,e.time,function(){for(var b=g.observers.slice(0),c=0,d=b.length;d>c;c++)a.accept(b[c]);return l})}(f)}return p(c,a),c}(h),x=function(a){function b(a){var b,c,d=this;this.subscriptions.push(new t(this.scheduler.clock));for(var e=this.subscriptions.length-1,f=new n,g=0,h=this.messages.length;h>g;g++)b=this.messages[g],c=b.value,function(c){f.add(d.scheduler.scheduleRelativeWithState(null,b.time,function(){return c.accept(a),l}))}(c);return m(function(){d.subscriptions[e]=new t(d.subscriptions[e].subscribe,d.scheduler.clock),f.dispose()})}function c(c,d){a.call(this,b),this.scheduler=c,this.messages=d,this.subscriptions=[]}return p(c,a),c}(h);return c.TestScheduler=function(a){function b(a,b){return a>b?1:b>a?-1:0}function c(){a.call(this,0,b)}return p(c,a),c.prototype.scheduleAbsoluteWithState=function(b,c,d){return c<=this.clock&&(c=this.clock+1),a.prototype.scheduleAbsoluteWithState.call(this,b,c,d)},c.prototype.add=function(a,b){return a+b},c.prototype.toDateTimeOffset=function(a){return new Date(a).getTime()},c.prototype.toRelative=function(a){return a},c.prototype.startWithTiming=function(a,b,c,d){var e,f,g=this.createObserver();return this.scheduleAbsoluteWithState(null,b,function(){return e=a(),l}),this.scheduleAbsoluteWithState(null,c,function(){return f=e.subscribe(g),l}),this.scheduleAbsoluteWithState(null,d,function(){return f.dispose(),l}),this.start(),g},c.prototype.startWithDispose=function(a,b){return this.startWithTiming(a,r.created,r.subscribed,b)},c.prototype.startWithCreate=function(a){return this.startWithTiming(a,r.created,r.subscribed,r.disposed)},c.prototype.createHotObservable=function(){var a=d(arguments,0);return new w(this,a)},c.prototype.createColdObservable=function(){var a=d(arguments,0);return new x(this,a)},c.prototype.createObserver=function(){return new v(this)},c}(j),c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.time.js b/js/libs/rxjs/rx.time.js new file mode 100644 index 0000000..c501d82 --- /dev/null +++ b/js/libs/rxjs/rx.time.js @@ -0,0 +1,1165 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Refernces + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + observableDefer = Observable.defer, + observableEmpty = Observable.empty, + observableNever = Observable.never, + observableThrow = Observable.throwException, + observableFromArray = Observable.fromArray, + timeoutScheduler = Rx.Scheduler.timeout, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + SerialDisposable = Rx.SerialDisposable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + Subject = Rx.Subject, + addRef = Rx.internals.addRef, + normalizeTime = Rx.Scheduler.normalize; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + var p = normalizeTime(period); + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime; + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + var now; + if (p > 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + var d = normalizeTime(dueTime); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(d, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + if (dueTime === period) { + return new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }); + } + return observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + scheduler || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + 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); + } + if (period === undefined) { + return observableTimerTimeSpan(dueTime, scheduler); + } + return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(dueTime, scheduler) { + var source = this; + 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); + }); + } + + function observableDelayDate(dueTime, scheduler) { + var self = this; + return observableDefer(function () { + var timeSpan = dueTime - scheduler.now(); + return observableDelayTimeSpan.call(self, timeSpan, scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate.call(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan.call(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + if (timeShiftOrScheduler === undefined) { + timeShift = timeSpan; + } + if (scheduler === undefined) { + scheduler = timeoutScheduler; + } + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + 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 (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + if (isSpan) { + nextSpan += timeShift; + } + if (isShift) { + nextShift += timeShift; + } + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onNext(x); + } + }, function (e) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onError(e); + } + observer.onError(e); + }, function () { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s, + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function (id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { + return; + } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + }; + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + if (newWindow) { + createTimer(newId); + } + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + var schedulerMethod, source = this; + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + if (dueTime instanceof Date) { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithAbsolute(dt, action); + }; + } else { + schedulerMethod = function (dt, action) { + scheduler.scheduleWithRelative(dt, action); + }; + } + return new AnonymousObservable(function (observer) { + var createTimer, + id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + subscription.setDisposable(original); + createTimer = function () { + var myId = id; + timer.setDisposable(schedulerMethod(dueTime, function () { + switched = id === myId; + var timerWins = switched; + if (timerWins) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + createTimer(); + original.setDisposable(source.subscribe(function (x) { + var onNextWins = !switched; + if (onNextWins) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + var onErrorWins = !switched; + if (onErrorWins) { + id++; + observer.onError(e); + } + }, function () { + var onCompletedWins = !switched; + if (onCompletedWins) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + 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) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + 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(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.time.min.js b/js/libs/rxjs/rx.time.min.js new file mode 100644 index 0000000..00bcd12 --- /dev/null +++ b/js/libs/rxjs/rx.time.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c,d){function e(a,b){return new n(function(c){return b.scheduleWithAbsolute(a,function(){c.onNext(0),c.onCompleted()})})}function f(a,b,c){var d=A(b);return new n(function(b){var e=0,f=a;return c.scheduleRecursiveWithAbsolute(f,function(a){var g;d>0&&(g=c.now(),f+=d,g>=f&&(f=g+d)),b.onNext(e++),a(f)})})}function g(a,b){var c=A(a);return new n(function(a){return b.scheduleWithRelative(c,function(){a.onNext(0),a.onCompleted()})})}function h(a,b,c){return a===b?new n(function(a){return c.schedulePeriodicWithState(0,b,function(b){return a.onNext(b),b+1})}):o(function(){return f(c.now()+a,b,c)})}function i(a,b){var c=this;return new n(function(d){var e,f=!1,g=new v,h=null,i=[],j=!1;return e=c.materialize().timestamp(b).subscribe(function(c){var e,k;"E"===c.value.kind?(i=[],i.push(c),h=c.value.exception,k=!j):(i.push({value:c.value,timestamp:c.timestamp+a}),k=!f,f=!0),k&&(null!==h?d.onError(h):(e=new u,g.setDisposable(e),e.setDisposable(b.scheduleRecursiveWithRelative(a,function(a){var c,e,g,k;if(null===h){j=!0;do g=null,i.length>0&&i[0].timestamp-b.now()<=0&&(g=i.shift().value),null!==g&&g.accept(d);while(null!==g);k=!1,e=0,i.length>0?(k=!0,e=Math.max(0,i[0].timestamp-b.now())):f=!1,c=h,j=!1,null!==c?d.onError(c):k&&a(e)}}))))}),new w(e,g)})}function j(a,b){var c=this;return o(function(){var d=a-b.now();return i.call(c,d,b)})}function k(a,b){return new n(function(c){function d(){g&&(g=!1,c.onNext(f)),e&&c.onCompleted()}var e,f,g;return new w(a.subscribe(function(a){g=!0,f=a},c.onError.bind(c),function(){e=!0}),b.subscribe(d,c.onError.bind(c),d))})}var l=c.Observable,m=l.prototype,n=c.AnonymousObservable,o=l.defer,p=l.empty,q=l.never,r=l.throwException,s=l.fromArray,t=c.Scheduler.timeout,u=c.SingleAssignmentDisposable,v=c.SerialDisposable,w=c.CompositeDisposable,x=c.RefCountDisposable,y=c.Subject,z=c.internals.addRef,A=c.Scheduler.normalize,B=l.interval=function(a,b){return b||(b=t),h(a,a,b)},C=l.timer=function(a,b,c){var i;return c||(c=t),b!==d&&"number"==typeof b?i=b:b!==d&&"object"==typeof b&&(c=b),a instanceof Date&&i===d?e(a.getTime(),c):a instanceof Date&&i!==d?(i=b,f(a.getTime(),i,c)):i===d?g(a,c):h(a,i,c)};return m.delay=function(a,b){return b||(b=t),a instanceof Date?j.call(this,a.getTime(),b):i.call(this,a,b)},m.throttle=function(a,b){b||(b=t);return this.throttleWithSelector(function(){return C(a,b)})},m.windowWithTime=function(a,b,c){var e,f=this;return b===d&&(e=a),c===d&&(c=t),"number"==typeof b?e=b:"object"==typeof b&&(e=a,c=b),new n(function(b){function d(){var a=new u,f=!1,g=!1;l.setDisposable(a),j===i?(f=!0,g=!0):i>j?f=!0:g=!0;var n=f?j:i,o=n-m;m=n,f&&(j+=e),g&&(i+=e),a.setDisposable(c.scheduleWithRelative(o,function(){var a;g&&(a=new y,k.push(a),b.onNext(z(a,h))),f&&(a=k.shift(),a.onCompleted()),d()}))}var g,h,i=e,j=a,k=[],l=new v,m=0;return g=new w(l),h=new x(g),k.push(new y),b.onNext(z(k[0],h)),d(),g.add(f.subscribe(function(a){var b,c;for(b=0;b0&&f-e[0].interval>=a;)d.onNext(e.shift().value)},d.onError.bind(d),function(){for(var c=b.now();e.length>0&&c-e[0].interval>=a;)d.onNext(e.shift().value);d.onCompleted()})})},m.takeLastWithTime=function(a,b,c){return this.takeLastBufferWithTime(a,b).selectMany(function(a){return s(a,c)})},m.takeLastBufferWithTime=function(a,b){var c=this;return b||(b=t),new n(function(d){var e=[];return c.subscribe(function(c){var d=b.now();for(e.push({interval:d,value:c});e.length>0&&d-e[0].interval>=a;)e.shift()},d.onError.bind(d),function(){for(var c=b.now(),f=[];e.length>0;){var g=e.shift();c-g.interval<=a&&f.push(g.value)}d.onNext(f),d.onCompleted()})})},m.takeWithTime=function(a,b){var c=this;return b||(b=t),new n(function(d){var e=b.scheduleWithRelative(a,function(){d.onCompleted()});return new w(e,c.subscribe(d))})},m.skipWithTime=function(a,b){var c=this;return b||(b=t),new n(function(d){var e=!1,f=b.scheduleWithRelative(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new w(f,g)})},m.skipUntilWithTime=function(a,b){b||(b=t);var c=this;return new n(function(d){var e=!1,f=b.scheduleWithAbsolute(a,function(){e=!0}),g=c.subscribe(function(a){e&&d.onNext(a)},d.onError.bind(d),d.onCompleted.bind(d));return new w(f,g)})},m.takeUntilWithTime=function(a,b){b||(b=t);var c=this;return new n(function(d){return new w(b.scheduleWithAbsolute(a,function(){d.onCompleted()}),c.subscribe(d))})},c}); \ No newline at end of file diff --git a/js/libs/rxjs/rx.virtualtime.js b/js/libs/rxjs/rx.virtualtime.js new file mode 100644 index 0000000..be9129f --- /dev/null +++ b/js/libs/rxjs/rx.virtualtime.js @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (factory) { + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + // Because of build optimizers + if (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Scheduler = Rx.Scheduler, + PriorityQueue = Rx.internals.PriorityQueue, + ScheduledItem = Rx.internals.ScheduledItem, + SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive, + disposableEmpty = Rx.Disposable.empty, + inherits = Rx.internals.inherits, + defaultSubComparer = Rx.helpers.defaultSubComparer; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + 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); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + 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; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (this.comparer(next.dueTime, this.clock) > 0) { + this.clock = next.dueTime; + } + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var next; + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (this.comparer(next.dueTime, this.clock) > 0) { + this.clock = next.dueTime; + } + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + + if (this.comparer(this.clock, dt) >= 0) { + throw new Error(argumentOutOfRange); + } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.queue.enqueue(si); + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (_super) { + inherits(HistoricalScheduler, _super); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + _super.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + /** + * @private + */ + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + return Rx; +})); \ No newline at end of file diff --git a/js/libs/rxjs/rx.virtualtime.min.js b/js/libs/rxjs/rx.virtualtime.min.js new file mode 100644 index 0000000..ce95353 --- /dev/null +++ b/js/libs/rxjs/rx.virtualtime.min.js @@ -0,0 +1 @@ +(function(a){var b={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},c=b[typeof window]&&window||this,d=b[typeof exports]&&exports&&!exports.nodeType&&exports,e=b[typeof module]&&module&&!module.nodeType&&module,f=(e&&e.exports===d&&d,b[typeof global]&&global);!f||f.global!==f&&f.window!==f||(c=f),"function"==typeof define&&define.amd?define(["rx","exports"],function(b,d){return c.Rx=a(c,d,b),c.Rx}):"object"==typeof module&&module&&module.exports===d?module.exports=a(c,module.exports,require("./rx")):c.Rx=a(c,{},c.Rx)}).call(this,function(a,b,c){var d=c.Scheduler,e=c.internals.PriorityQueue,f=c.internals.ScheduledItem,g=c.internals.SchedulePeriodicRecursive,h=c.Disposable.empty,i=c.internals.inherits,j=c.helpers.defaultSubComparer;return c.VirtualTimeScheduler=function(a){function b(){throw new Error("Not implemented")}function c(){return this.toDateTimeOffset(this.clock)}function d(a,b){return this.scheduleAbsoluteWithState(a,this.clock,b)}function j(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b),c)}function k(a,b,c){return this.scheduleRelativeWithState(a,this.toRelative(b-this.now()),c)}function l(a,b){return b(),h}function m(b,f){this.clock=b,this.comparer=f,this.isEnabled=!1,this.queue=new e(1024),a.call(this,c,d,j,k)}i(m,a);var n=m.prototype;return n.add=b,n.toDateTimeOffset=b,n.toRelative=b,n.schedulePeriodicWithState=function(a,b,c){var d=new g(this,a,b,c);return d.start()},n.scheduleRelativeWithState=function(a,b,c){var d=this.add(this.clock,b);return this.scheduleAbsoluteWithState(a,d,c)},n.scheduleRelative=function(a,b){return this.scheduleRelativeWithState(b,a,l)},n.start=function(){var a;if(!this.isEnabled){this.isEnabled=!0;do a=this.getNext(),null!==a?(this.comparer(a.dueTime,this.clock)>0&&(this.clock=a.dueTime),a.invoke()):this.isEnabled=!1;while(this.isEnabled)}},n.stop=function(){this.isEnabled=!1},n.advanceTo=function(a){var b,c=this.comparer(this.clock,a);if(this.comparer(this.clock,a)>0)throw new Error(argumentOutOfRange);if(0!==c&&!this.isEnabled){this.isEnabled=!0;do b=this.getNext(),null!==b&&this.comparer(b.dueTime,a)<=0?(this.comparer(b.dueTime,this.clock)>0&&(this.clock=b.dueTime),b.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=a}},n.advanceBy=function(a){var b=this.add(this.clock,a),c=this.comparer(this.clock,b);if(c>0)throw new Error(argumentOutOfRange);0!==c&&this.advanceTo(b)},n.sleep=function(a){var b=this.add(this.clock,a);if(this.comparer(this.clock,b)>=0)throw new Error(argumentOutOfRange);this.clock=b},n.getNext=function(){for(var a;this.queue.length>0;){if(a=this.queue.peek(),!a.isCancelled())return a;this.queue.dequeue()}return null},n.scheduleAbsolute=function(a,b){return this.scheduleAbsoluteWithState(b,a,l)},n.scheduleAbsoluteWithState=function(a,b,c){var d=this,e=function(a,b){return d.queue.remove(g),c(a,b)},g=new f(d,a,e,b,d.comparer);return d.queue.enqueue(g),g.disposable},m}(d),c.HistoricalScheduler=function(a){function b(b,c){var d=null==b?0:b,e=c||j;a.call(this,d,e)}i(b,a);var c=b.prototype;return c.add=function(a,b){return a+b},c.toDateTimeOffset=function(a){return new Date(a).getTime()},c.toRelative=function(a){return a},b}(c.VirtualTimeScheduler),c}); \ No newline at end of file