UNPKG

208 kBJavaScriptView Raw
1// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
2
3;(function (undefined) {
4
5 var objectTypes = {
6 'function': true,
7 'object': true
8 };
9
10 function checkGlobal(value) {
11 return (value && value.Object === Object) ? value : null;
12 }
13
14 var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
15 var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
16 var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
17 var freeSelf = checkGlobal(objectTypes[typeof self] && self);
18 var freeWindow = checkGlobal(objectTypes[typeof window] && window);
19 var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
20 var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
21 var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
22
23 var Rx = {
24 internals: {},
25 config: {
26 Promise: root.Promise
27 },
28 helpers: { }
29 };
30
31 // Defaults
32 var noop = Rx.helpers.noop = function () { },
33 identity = Rx.helpers.identity = function (x) { return x; },
34 defaultNow = Rx.helpers.defaultNow = Date.now,
35 defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
36 defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
37 defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
38 defaultError = Rx.helpers.defaultError = function (err) { throw err; },
39 isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
40 isFunction = Rx.helpers.isFunction = (function () {
41
42 var isFn = function (value) {
43 return typeof value == 'function' || false;
44 };
45
46 // fallback for older versions of Chrome and Safari
47 if (isFn(/x/)) {
48 isFn = function(value) {
49 return typeof value == 'function' && toString.call(value) == '[object Function]';
50 };
51 }
52
53 return isFn;
54 }());
55
56 function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
57
58 var errorObj = {e: {}};
59
60 function tryCatcherGen(tryCatchTarget) {
61 return function tryCatcher() {
62 try {
63 return tryCatchTarget.apply(this, arguments);
64 } catch (e) {
65 errorObj.e = e;
66 return errorObj;
67 }
68 };
69 }
70
71 var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
72 if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
73 return tryCatcherGen(fn);
74 };
75
76 function thrower(e) {
77 throw e;
78 }
79
80 Rx.config.longStackSupport = false;
81 var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
82 hasStacks = !!stacks.e && !!stacks.e.stack;
83
84 // All code after this point will be filtered from stack traces reported by RxJS
85 var rStartingLine = captureLine(), rFileName;
86
87 var STACK_JUMP_SEPARATOR = 'From previous event:';
88
89 function makeStackTraceLong(error, observable) {
90 // If possible, transform the error stack trace by removing Node and RxJS
91 // cruft, then concatenating with the stack trace of `observable`.
92 if (hasStacks &&
93 observable.stack &&
94 typeof error === 'object' &&
95 error !== null &&
96 error.stack &&
97 error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
98 ) {
99 var stacks = [];
100 for (var o = observable; !!o; o = o.source) {
101 if (o.stack) {
102 stacks.unshift(o.stack);
103 }
104 }
105 stacks.unshift(error.stack);
106
107 var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
108 error.stack = filterStackString(concatedStacks);
109 }
110 }
111
112 function filterStackString(stackString) {
113 var lines = stackString.split('\n'), desiredLines = [];
114 for (var i = 0, len = lines.length; i < len; i++) {
115 var line = lines[i];
116
117 if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
118 desiredLines.push(line);
119 }
120 }
121 return desiredLines.join('\n');
122 }
123
124 function isInternalFrame(stackLine) {
125 var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
126 if (!fileNameAndLineNumber) {
127 return false;
128 }
129 var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
130
131 return fileName === rFileName &&
132 lineNumber >= rStartingLine &&
133 lineNumber <= rEndingLine;
134 }
135
136 function isNodeFrame(stackLine) {
137 return stackLine.indexOf('(module.js:') !== -1 ||
138 stackLine.indexOf('(node.js:') !== -1;
139 }
140
141 function captureLine() {
142 if (!hasStacks) { return; }
143
144 try {
145 throw new Error();
146 } catch (e) {
147 var lines = e.stack.split('\n');
148 var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
149 var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
150 if (!fileNameAndLineNumber) { return; }
151
152 rFileName = fileNameAndLineNumber[0];
153 return fileNameAndLineNumber[1];
154 }
155 }
156
157 function getFileNameAndLineNumber(stackLine) {
158 // Named functions: 'at functionName (filename:lineNumber:columnNumber)'
159 var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
160 if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
161
162 // Anonymous functions: 'at filename:lineNumber:columnNumber'
163 var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
164 if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
165
166 // Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
167 var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
168 if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
169 }
170
171 var EmptyError = Rx.EmptyError = function() {
172 this.message = 'Sequence contains no elements.';
173 Error.call(this);
174 };
175 EmptyError.prototype = Object.create(Error.prototype);
176 EmptyError.prototype.name = 'EmptyError';
177
178 var ObjectDisposedError = Rx.ObjectDisposedError = function() {
179 this.message = 'Object has been disposed';
180 Error.call(this);
181 };
182 ObjectDisposedError.prototype = Object.create(Error.prototype);
183 ObjectDisposedError.prototype.name = 'ObjectDisposedError';
184
185 var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
186 this.message = 'Argument out of range';
187 Error.call(this);
188 };
189 ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
190 ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';
191
192 var NotSupportedError = Rx.NotSupportedError = function (message) {
193 this.message = message || 'This operation is not supported';
194 Error.call(this);
195 };
196 NotSupportedError.prototype = Object.create(Error.prototype);
197 NotSupportedError.prototype.name = 'NotSupportedError';
198
199 var NotImplementedError = Rx.NotImplementedError = function (message) {
200 this.message = message || 'This operation is not implemented';
201 Error.call(this);
202 };
203 NotImplementedError.prototype = Object.create(Error.prototype);
204 NotImplementedError.prototype.name = 'NotImplementedError';
205
206 var notImplemented = Rx.helpers.notImplemented = function () {
207 throw new NotImplementedError();
208 };
209
210 var notSupported = Rx.helpers.notSupported = function () {
211 throw new NotSupportedError();
212 };
213
214 // Shim in iterator support
215 var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
216 '_es6shim_iterator_';
217 // Bug for mozilla version
218 if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
219 $iterator$ = '@@iterator';
220 }
221
222 var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
223
224 var isIterable = Rx.helpers.isIterable = function (o) {
225 return o && o[$iterator$] !== undefined;
226 };
227
228 var isArrayLike = Rx.helpers.isArrayLike = function (o) {
229 return o && o.length !== undefined;
230 };
231
232 Rx.helpers.iterator = $iterator$;
233
234 var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
235 if (typeof thisArg === 'undefined') { return func; }
236 switch(argCount) {
237 case 0:
238 return function() {
239 return func.call(thisArg)
240 };
241 case 1:
242 return function(arg) {
243 return func.call(thisArg, arg);
244 };
245 case 2:
246 return function(value, index) {
247 return func.call(thisArg, value, index);
248 };
249 case 3:
250 return function(value, index, collection) {
251 return func.call(thisArg, value, index, collection);
252 };
253 }
254
255 return function() {
256 return func.apply(thisArg, arguments);
257 };
258 };
259
260 /** Used to determine if values are of the language type Object */
261 var dontEnums = ['toString',
262 'toLocaleString',
263 'valueOf',
264 'hasOwnProperty',
265 'isPrototypeOf',
266 'propertyIsEnumerable',
267 'constructor'],
268 dontEnumsLength = dontEnums.length;
269
270var argsTag = '[object Arguments]',
271 arrayTag = '[object Array]',
272 boolTag = '[object Boolean]',
273 dateTag = '[object Date]',
274 errorTag = '[object Error]',
275 funcTag = '[object Function]',
276 mapTag = '[object Map]',
277 numberTag = '[object Number]',
278 objectTag = '[object Object]',
279 regexpTag = '[object RegExp]',
280 setTag = '[object Set]',
281 stringTag = '[object String]',
282 weakMapTag = '[object WeakMap]';
283
284var arrayBufferTag = '[object ArrayBuffer]',
285 float32Tag = '[object Float32Array]',
286 float64Tag = '[object Float64Array]',
287 int8Tag = '[object Int8Array]',
288 int16Tag = '[object Int16Array]',
289 int32Tag = '[object Int32Array]',
290 uint8Tag = '[object Uint8Array]',
291 uint8ClampedTag = '[object Uint8ClampedArray]',
292 uint16Tag = '[object Uint16Array]',
293 uint32Tag = '[object Uint32Array]';
294
295var typedArrayTags = {};
296typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
297typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
298typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
299typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
300typedArrayTags[uint32Tag] = true;
301typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
302typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
303typedArrayTags[dateTag] = typedArrayTags[errorTag] =
304typedArrayTags[funcTag] = typedArrayTags[mapTag] =
305typedArrayTags[numberTag] = typedArrayTags[objectTag] =
306typedArrayTags[regexpTag] = typedArrayTags[setTag] =
307typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
308
309var objectProto = Object.prototype,
310 hasOwnProperty = objectProto.hasOwnProperty,
311 objToString = objectProto.toString,
312 MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
313
314var keys = Object.keys || (function() {
315 var hasOwnProperty = Object.prototype.hasOwnProperty,
316 hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
317 dontEnums = [
318 'toString',
319 'toLocaleString',
320 'valueOf',
321 'hasOwnProperty',
322 'isPrototypeOf',
323 'propertyIsEnumerable',
324 'constructor'
325 ],
326 dontEnumsLength = dontEnums.length;
327
328 return function(obj) {
329 if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
330 throw new TypeError('Object.keys called on non-object');
331 }
332
333 var result = [], prop, i;
334
335 for (prop in obj) {
336 if (hasOwnProperty.call(obj, prop)) {
337 result.push(prop);
338 }
339 }
340
341 if (hasDontEnumBug) {
342 for (i = 0; i < dontEnumsLength; i++) {
343 if (hasOwnProperty.call(obj, dontEnums[i])) {
344 result.push(dontEnums[i]);
345 }
346 }
347 }
348 return result;
349 };
350 }());
351
352function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
353 var objProps = keys(object),
354 objLength = objProps.length,
355 othProps = keys(other),
356 othLength = othProps.length;
357
358 if (objLength !== othLength && !isLoose) {
359 return false;
360 }
361 var index = objLength, key;
362 while (index--) {
363 key = objProps[index];
364 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
365 return false;
366 }
367 }
368 var skipCtor = isLoose;
369 while (++index < objLength) {
370 key = objProps[index];
371 var objValue = object[key],
372 othValue = other[key],
373 result;
374
375 if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
376 return false;
377 }
378 skipCtor || (skipCtor = key === 'constructor');
379 }
380 if (!skipCtor) {
381 var objCtor = object.constructor,
382 othCtor = other.constructor;
383
384 if (objCtor !== othCtor &&
385 ('constructor' in object && 'constructor' in other) &&
386 !(typeof objCtor === 'function' && objCtor instanceof objCtor &&
387 typeof othCtor === 'function' && othCtor instanceof othCtor)) {
388 return false;
389 }
390 }
391 return true;
392}
393
394function equalByTag(object, other, tag) {
395 switch (tag) {
396 case boolTag:
397 case dateTag:
398 return +object === +other;
399
400 case errorTag:
401 return object.name === other.name && object.message === other.message;
402
403 case numberTag:
404 return (object !== +object) ?
405 other !== +other :
406 object === +other;
407
408 case regexpTag:
409 case stringTag:
410 return object === (other + '');
411 }
412 return false;
413}
414
415var isObject = Rx.internals.isObject = function(value) {
416 var type = typeof value;
417 return !!value && (type === 'object' || type === 'function');
418};
419
420function isObjectLike(value) {
421 return !!value && typeof value === 'object';
422}
423
424function isLength(value) {
425 return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
426}
427
428var isHostObject = (function() {
429 try {
430 Object({ 'toString': 0 } + '');
431 } catch(e) {
432 return function() { return false; };
433 }
434 return function(value) {
435 return typeof value.toString !== 'function' && typeof (value + '') === 'string';
436 };
437}());
438
439function isTypedArray(value) {
440 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
441}
442
443var isArray = Array.isArray || function(value) {
444 return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
445};
446
447function arraySome (array, predicate) {
448 var index = -1,
449 length = array.length;
450
451 while (++index < length) {
452 if (predicate(array[index], index, array)) {
453 return true;
454 }
455 }
456 return false;
457}
458
459function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
460 var index = -1,
461 arrLength = array.length,
462 othLength = other.length;
463
464 if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
465 return false;
466 }
467 // Ignore non-index properties.
468 while (++index < arrLength) {
469 var arrValue = array[index],
470 othValue = other[index],
471 result;
472
473 if (result !== undefined) {
474 if (result) {
475 continue;
476 }
477 return false;
478 }
479 // Recursively compare arrays (susceptible to call stack limits).
480 if (isLoose) {
481 if (!arraySome(other, function(othValue) {
482 return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
483 })) {
484 return false;
485 }
486 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
487 return false;
488 }
489 }
490 return true;
491}
492
493function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
494 var objIsArr = isArray(object),
495 othIsArr = isArray(other),
496 objTag = arrayTag,
497 othTag = arrayTag;
498
499 if (!objIsArr) {
500 objTag = objToString.call(object);
501 if (objTag === argsTag) {
502 objTag = objectTag;
503 } else if (objTag !== objectTag) {
504 objIsArr = isTypedArray(object);
505 }
506 }
507 if (!othIsArr) {
508 othTag = objToString.call(other);
509 if (othTag === argsTag) {
510 othTag = objectTag;
511 }
512 }
513 var objIsObj = objTag === objectTag && !isHostObject(object),
514 othIsObj = othTag === objectTag && !isHostObject(other),
515 isSameTag = objTag === othTag;
516
517 if (isSameTag && !(objIsArr || objIsObj)) {
518 return equalByTag(object, other, objTag);
519 }
520 if (!isLoose) {
521 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
522 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
523
524 if (objIsWrapped || othIsWrapped) {
525 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
526 }
527 }
528 if (!isSameTag) {
529 return false;
530 }
531 // Assume cyclic values are equal.
532 // For more information on detecting circular references see https://es5.github.io/#JO.
533 stackA || (stackA = []);
534 stackB || (stackB = []);
535
536 var length = stackA.length;
537 while (length--) {
538 if (stackA[length] === object) {
539 return stackB[length] === other;
540 }
541 }
542 // Add `object` and `other` to the stack of traversed objects.
543 stackA.push(object);
544 stackB.push(other);
545
546 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
547
548 stackA.pop();
549 stackB.pop();
550
551 return result;
552}
553
554function baseIsEqual(value, other, isLoose, stackA, stackB) {
555 if (value === other) {
556 return true;
557 }
558 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
559 return value !== value && other !== other;
560 }
561 return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
562}
563
564var isEqual = Rx.internals.isEqual = function (value, other) {
565 return baseIsEqual(value, other);
566};
567
568 var hasProp = {}.hasOwnProperty,
569 slice = Array.prototype.slice;
570
571 var inherits = Rx.internals.inherits = function (child, parent) {
572 function __() { this.constructor = child; }
573 __.prototype = parent.prototype;
574 child.prototype = new __();
575 };
576
577 var addProperties = Rx.internals.addProperties = function (obj) {
578 for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
579 for (var idx = 0, ln = sources.length; idx < ln; idx++) {
580 var source = sources[idx];
581 for (var prop in source) {
582 obj[prop] = source[prop];
583 }
584 }
585 };
586
587 // Rx Utils
588 var addRef = Rx.internals.addRef = function (xs, r) {
589 return new AnonymousObservable(function (observer) {
590 return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));
591 });
592 };
593
594 function arrayInitialize(count, factory) {
595 var a = new Array(count);
596 for (var i = 0; i < count; i++) {
597 a[i] = factory();
598 }
599 return a;
600 }
601
602 /**
603 * Represents a group of disposable resources that are disposed together.
604 * @constructor
605 */
606 var CompositeDisposable = Rx.CompositeDisposable = function () {
607 var args = [], i, len;
608 if (Array.isArray(arguments[0])) {
609 args = arguments[0];
610 } else {
611 len = arguments.length;
612 args = new Array(len);
613 for(i = 0; i < len; i++) { args[i] = arguments[i]; }
614 }
615 this.disposables = args;
616 this.isDisposed = false;
617 this.length = args.length;
618 };
619
620 var CompositeDisposablePrototype = CompositeDisposable.prototype;
621
622 /**
623 * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
624 * @param {Mixed} item Disposable to add.
625 */
626 CompositeDisposablePrototype.add = function (item) {
627 if (this.isDisposed) {
628 item.dispose();
629 } else {
630 this.disposables.push(item);
631 this.length++;
632 }
633 };
634
635 /**
636 * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
637 * @param {Mixed} item Disposable to remove.
638 * @returns {Boolean} true if found; false otherwise.
639 */
640 CompositeDisposablePrototype.remove = function (item) {
641 var shouldDispose = false;
642 if (!this.isDisposed) {
643 var idx = this.disposables.indexOf(item);
644 if (idx !== -1) {
645 shouldDispose = true;
646 this.disposables.splice(idx, 1);
647 this.length--;
648 item.dispose();
649 }
650 }
651 return shouldDispose;
652 };
653
654 /**
655 * Disposes all disposables in the group and removes them from the group.
656 */
657 CompositeDisposablePrototype.dispose = function () {
658 if (!this.isDisposed) {
659 this.isDisposed = true;
660 var len = this.disposables.length, currentDisposables = new Array(len);
661 for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
662 this.disposables = [];
663 this.length = 0;
664
665 for (i = 0; i < len; i++) {
666 currentDisposables[i].dispose();
667 }
668 }
669 };
670
671 /**
672 * Provides a set of static methods for creating Disposables.
673 * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
674 */
675 var Disposable = Rx.Disposable = function (action) {
676 this.isDisposed = false;
677 this.action = action || noop;
678 };
679
680 /** Performs the task of cleaning up resources. */
681 Disposable.prototype.dispose = function () {
682 if (!this.isDisposed) {
683 this.action();
684 this.isDisposed = true;
685 }
686 };
687
688 /**
689 * Creates a disposable object that invokes the specified action when disposed.
690 * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
691 * @return {Disposable} The disposable object that runs the given action upon disposal.
692 */
693 var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
694
695 /**
696 * Gets the disposable that does nothing when disposed.
697 */
698 var disposableEmpty = Disposable.empty = { dispose: noop };
699
700 /**
701 * Validates whether the given object is a disposable
702 * @param {Object} Object to test whether it has a dispose method
703 * @returns {Boolean} true if a disposable object, else false.
704 */
705 var isDisposable = Disposable.isDisposable = function (d) {
706 return d && isFunction(d.dispose);
707 };
708
709 var checkDisposed = Disposable.checkDisposed = function (disposable) {
710 if (disposable.isDisposed) { throw new ObjectDisposedError(); }
711 };
712
713 var disposableFixup = Disposable._fixup = function (result) {
714 return isDisposable(result) ? result : disposableEmpty;
715 };
716
717 // Single assignment
718 var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
719 this.isDisposed = false;
720 this.current = null;
721 };
722 SingleAssignmentDisposable.prototype.getDisposable = function () {
723 return this.current;
724 };
725 SingleAssignmentDisposable.prototype.setDisposable = function (value) {
726 if (this.current) { throw new Error('Disposable has already been assigned'); }
727 var shouldDispose = this.isDisposed;
728 !shouldDispose && (this.current = value);
729 shouldDispose && value && value.dispose();
730 };
731 SingleAssignmentDisposable.prototype.dispose = function () {
732 if (!this.isDisposed) {
733 this.isDisposed = true;
734 var old = this.current;
735 this.current = null;
736 old && old.dispose();
737 }
738 };
739
740 // Multiple assignment disposable
741 var SerialDisposable = Rx.SerialDisposable = function () {
742 this.isDisposed = false;
743 this.current = null;
744 };
745 SerialDisposable.prototype.getDisposable = function () {
746 return this.current;
747 };
748 SerialDisposable.prototype.setDisposable = function (value) {
749 var shouldDispose = this.isDisposed;
750 if (!shouldDispose) {
751 var old = this.current;
752 this.current = value;
753 }
754 old && old.dispose();
755 shouldDispose && value && value.dispose();
756 };
757 SerialDisposable.prototype.dispose = function () {
758 if (!this.isDisposed) {
759 this.isDisposed = true;
760 var old = this.current;
761 this.current = null;
762 }
763 old && old.dispose();
764 };
765
766 var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {
767 this._first = first;
768 this._second = second;
769 this.isDisposed = false;
770 };
771
772 BinaryDisposable.prototype.dispose = function () {
773 if (!this.isDisposed) {
774 this.isDisposed = true;
775 var old1 = this._first;
776 this._first = null;
777 old1 && old1.dispose();
778 var old2 = this._second;
779 this._second = null;
780 old2 && old2.dispose();
781 }
782 };
783
784 var NAryDisposable = Rx.NAryDisposable = function (disposables) {
785 this._disposables = disposables;
786 this.isDisposed = false;
787 };
788
789 NAryDisposable.prototype.dispose = function () {
790 if (!this.isDisposed) {
791 this.isDisposed = true;
792 for (var i = 0, len = this._disposables.length; i < len; i++) {
793 this._disposables[i].dispose();
794 }
795 this._disposables.length = 0;
796 }
797 };
798
799 /**
800 * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
801 */
802 var RefCountDisposable = Rx.RefCountDisposable = (function () {
803
804 function InnerDisposable(disposable) {
805 this.disposable = disposable;
806 this.disposable.count++;
807 this.isInnerDisposed = false;
808 }
809
810 InnerDisposable.prototype.dispose = function () {
811 if (!this.disposable.isDisposed && !this.isInnerDisposed) {
812 this.isInnerDisposed = true;
813 this.disposable.count--;
814 if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
815 this.disposable.isDisposed = true;
816 this.disposable.underlyingDisposable.dispose();
817 }
818 }
819 };
820
821 /**
822 * Initializes a new instance of the RefCountDisposable with the specified disposable.
823 * @constructor
824 * @param {Disposable} disposable Underlying disposable.
825 */
826 function RefCountDisposable(disposable) {
827 this.underlyingDisposable = disposable;
828 this.isDisposed = false;
829 this.isPrimaryDisposed = false;
830 this.count = 0;
831 }
832
833 /**
834 * Disposes the underlying disposable only when all dependent disposables have been disposed
835 */
836 RefCountDisposable.prototype.dispose = function () {
837 if (!this.isDisposed && !this.isPrimaryDisposed) {
838 this.isPrimaryDisposed = true;
839 if (this.count === 0) {
840 this.isDisposed = true;
841 this.underlyingDisposable.dispose();
842 }
843 }
844 };
845
846 /**
847 * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
848 * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
849 */
850 RefCountDisposable.prototype.getDisposable = function () {
851 return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
852 };
853
854 return RefCountDisposable;
855 })();
856
857 function ScheduledDisposable(scheduler, disposable) {
858 this.scheduler = scheduler;
859 this.disposable = disposable;
860 this.isDisposed = false;
861 }
862
863 function scheduleItem(s, self) {
864 if (!self.isDisposed) {
865 self.isDisposed = true;
866 self.disposable.dispose();
867 }
868 }
869
870 ScheduledDisposable.prototype.dispose = function () {
871 this.scheduler.schedule(this, scheduleItem);
872 };
873
874 var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
875 this.scheduler = scheduler;
876 this.state = state;
877 this.action = action;
878 this.dueTime = dueTime;
879 this.comparer = comparer || defaultSubComparer;
880 this.disposable = new SingleAssignmentDisposable();
881 };
882
883 ScheduledItem.prototype.invoke = function () {
884 this.disposable.setDisposable(this.invokeCore());
885 };
886
887 ScheduledItem.prototype.compareTo = function (other) {
888 return this.comparer(this.dueTime, other.dueTime);
889 };
890
891 ScheduledItem.prototype.isCancelled = function () {
892 return this.disposable.isDisposed;
893 };
894
895 ScheduledItem.prototype.invokeCore = function () {
896 return disposableFixup(this.action(this.scheduler, this.state));
897 };
898
899 /** Provides a set of static properties to access commonly used schedulers. */
900 var Scheduler = Rx.Scheduler = (function () {
901
902 function Scheduler() { }
903
904 /** Determines whether the given object is a scheduler */
905 Scheduler.isScheduler = function (s) {
906 return s instanceof Scheduler;
907 };
908
909 var schedulerProto = Scheduler.prototype;
910
911 /**
912 * Schedules an action to be executed.
913 * @param state State passed to the action to be executed.
914 * @param {Function} action Action to be executed.
915 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
916 */
917 schedulerProto.schedule = function (state, action) {
918 throw new NotImplementedError();
919 };
920
921 /**
922 * Schedules an action to be executed after dueTime.
923 * @param state State passed to the action to be executed.
924 * @param {Function} action Action to be executed.
925 * @param {Number} dueTime Relative time after which to execute the action.
926 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
927 */
928 schedulerProto.scheduleFuture = function (state, dueTime, action) {
929 var dt = dueTime;
930 dt instanceof Date && (dt = dt - this.now());
931 dt = Scheduler.normalize(dt);
932
933 if (dt === 0) { return this.schedule(state, action); }
934
935 return this._scheduleFuture(state, dt, action);
936 };
937
938 schedulerProto._scheduleFuture = function (state, dueTime, action) {
939 throw new NotImplementedError();
940 };
941
942 /** Gets the current time according to the local machine's system clock. */
943 Scheduler.now = defaultNow;
944
945 /** Gets the current time according to the local machine's system clock. */
946 Scheduler.prototype.now = defaultNow;
947
948 /**
949 * Normalizes the specified TimeSpan value to a positive value.
950 * @param {Number} timeSpan The time span value to normalize.
951 * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
952 */
953 Scheduler.normalize = function (timeSpan) {
954 timeSpan < 0 && (timeSpan = 0);
955 return timeSpan;
956 };
957
958 return Scheduler;
959 }());
960
961 var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
962
963 (function (schedulerProto) {
964
965 function invokeRecImmediate(scheduler, pair) {
966 var state = pair[0], action = pair[1], group = new CompositeDisposable();
967 action(state, innerAction);
968 return group;
969
970 function innerAction(state2) {
971 var isAdded = false, isDone = false;
972
973 var d = scheduler.schedule(state2, scheduleWork);
974 if (!isDone) {
975 group.add(d);
976 isAdded = true;
977 }
978
979 function scheduleWork(_, state3) {
980 if (isAdded) {
981 group.remove(d);
982 } else {
983 isDone = true;
984 }
985 action(state3, innerAction);
986 return disposableEmpty;
987 }
988 }
989 }
990
991 function invokeRecDate(scheduler, pair) {
992 var state = pair[0], action = pair[1], group = new CompositeDisposable();
993 action(state, innerAction);
994 return group;
995
996 function innerAction(state2, dueTime1) {
997 var isAdded = false, isDone = false;
998
999 var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);
1000 if (!isDone) {
1001 group.add(d);
1002 isAdded = true;
1003 }
1004
1005 function scheduleWork(_, state3) {
1006 if (isAdded) {
1007 group.remove(d);
1008 } else {
1009 isDone = true;
1010 }
1011 action(state3, innerAction);
1012 return disposableEmpty;
1013 }
1014 }
1015 }
1016
1017 /**
1018 * Schedules an action to be executed recursively.
1019 * @param {Mixed} state State passed to the action to be executed.
1020 * @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.
1021 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1022 */
1023 schedulerProto.scheduleRecursive = function (state, action) {
1024 return this.schedule([state, action], invokeRecImmediate);
1025 };
1026
1027 /**
1028 * Schedules an action to be executed recursively after a specified relative or absolute due time.
1029 * @param {Mixed} state State passed to the action to be executed.
1030 * @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.
1031 * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.
1032 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1033 */
1034 schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {
1035 return this.scheduleFuture([state, action], dueTime, invokeRecDate);
1036 };
1037
1038 }(Scheduler.prototype));
1039
1040 (function (schedulerProto) {
1041
1042 /**
1043 * 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.
1044 * @param {Mixed} state Initial state passed to the action upon the first iteration.
1045 * @param {Number} period Period for running the work periodically.
1046 * @param {Function} action Action to be executed, potentially updating the state.
1047 * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
1048 */
1049 schedulerProto.schedulePeriodic = function(state, period, action) {
1050 if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
1051 period = normalizeTime(period);
1052 var s = state, id = root.setInterval(function () { s = action(s); }, period);
1053 return disposableCreate(function () { root.clearInterval(id); });
1054 };
1055
1056 }(Scheduler.prototype));
1057
1058 (function (schedulerProto) {
1059 /**
1060 * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
1061 * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
1062 * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
1063 */
1064 schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
1065 return new CatchScheduler(this, handler);
1066 };
1067 }(Scheduler.prototype));
1068
1069 var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
1070 function createTick(self) {
1071 return function tick(command, recurse) {
1072 recurse(0, self._period);
1073 var state = tryCatch(self._action)(self._state);
1074 if (state === errorObj) {
1075 self._cancel.dispose();
1076 thrower(state.e);
1077 }
1078 self._state = state;
1079 };
1080 }
1081
1082 function SchedulePeriodicRecursive(scheduler, state, period, action) {
1083 this._scheduler = scheduler;
1084 this._state = state;
1085 this._period = period;
1086 this._action = action;
1087 }
1088
1089 SchedulePeriodicRecursive.prototype.start = function () {
1090 var d = new SingleAssignmentDisposable();
1091 this._cancel = d;
1092 d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
1093
1094 return d;
1095 };
1096
1097 return SchedulePeriodicRecursive;
1098 }());
1099
1100 /** Gets a scheduler that schedules work immediately on the current thread. */
1101 var ImmediateScheduler = (function (__super__) {
1102 inherits(ImmediateScheduler, __super__);
1103 function ImmediateScheduler() {
1104 __super__.call(this);
1105 }
1106
1107 ImmediateScheduler.prototype.schedule = function (state, action) {
1108 return disposableFixup(action(this, state));
1109 };
1110
1111 return ImmediateScheduler;
1112 }(Scheduler));
1113
1114 var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();
1115
1116 /**
1117 * Gets a scheduler that schedules work as soon as possible on the current thread.
1118 */
1119 var CurrentThreadScheduler = (function (__super__) {
1120 var queue;
1121
1122 function runTrampoline () {
1123 while (queue.length > 0) {
1124 var item = queue.dequeue();
1125 !item.isCancelled() && item.invoke();
1126 }
1127 }
1128
1129 inherits(CurrentThreadScheduler, __super__);
1130 function CurrentThreadScheduler() {
1131 __super__.call(this);
1132 }
1133
1134 CurrentThreadScheduler.prototype.schedule = function (state, action) {
1135 var si = new ScheduledItem(this, state, action, this.now());
1136
1137 if (!queue) {
1138 queue = new PriorityQueue(4);
1139 queue.enqueue(si);
1140
1141 var result = tryCatch(runTrampoline)();
1142 queue = null;
1143 if (result === errorObj) { thrower(result.e); }
1144 } else {
1145 queue.enqueue(si);
1146 }
1147 return si.disposable;
1148 };
1149
1150 CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };
1151
1152 return CurrentThreadScheduler;
1153 }(Scheduler));
1154
1155 var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();
1156
1157 var scheduleMethod, clearMethod;
1158
1159 var localTimer = (function () {
1160 var localSetTimeout, localClearTimeout = noop;
1161 if (!!root.setTimeout) {
1162 localSetTimeout = root.setTimeout;
1163 localClearTimeout = root.clearTimeout;
1164 } else if (!!root.WScript) {
1165 localSetTimeout = function (fn, time) {
1166 root.WScript.Sleep(time);
1167 fn();
1168 };
1169 } else {
1170 throw new NotSupportedError();
1171 }
1172
1173 return {
1174 setTimeout: localSetTimeout,
1175 clearTimeout: localClearTimeout
1176 };
1177 }());
1178 var localSetTimeout = localTimer.setTimeout,
1179 localClearTimeout = localTimer.clearTimeout;
1180
1181 (function () {
1182
1183 var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
1184
1185 clearMethod = function (handle) {
1186 delete tasksByHandle[handle];
1187 };
1188
1189 function runTask(handle) {
1190 if (currentlyRunning) {
1191 localSetTimeout(function () { runTask(handle); }, 0);
1192 } else {
1193 var task = tasksByHandle[handle];
1194 if (task) {
1195 currentlyRunning = true;
1196 var result = tryCatch(task)();
1197 clearMethod(handle);
1198 currentlyRunning = false;
1199 if (result === errorObj) { thrower(result.e); }
1200 }
1201 }
1202 }
1203
1204 var reNative = new RegExp('^' +
1205 String(toString)
1206 .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1207 .replace(/toString| for [^\]]+/g, '.*?') + '$'
1208 );
1209
1210 var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
1211 !reNative.test(setImmediate) && setImmediate;
1212
1213 function postMessageSupported () {
1214 // Ensure not in a worker
1215 if (!root.postMessage || root.importScripts) { return false; }
1216 var isAsync = false, oldHandler = root.onmessage;
1217 // Test for async
1218 root.onmessage = function () { isAsync = true; };
1219 root.postMessage('', '*');
1220 root.onmessage = oldHandler;
1221
1222 return isAsync;
1223 }
1224
1225 // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
1226 if (isFunction(setImmediate)) {
1227 scheduleMethod = function (action) {
1228 var id = nextHandle++;
1229 tasksByHandle[id] = action;
1230 setImmediate(function () { runTask(id); });
1231
1232 return id;
1233 };
1234 } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
1235 scheduleMethod = function (action) {
1236 var id = nextHandle++;
1237 tasksByHandle[id] = action;
1238 process.nextTick(function () { runTask(id); });
1239
1240 return id;
1241 };
1242 } else if (postMessageSupported()) {
1243 var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
1244
1245 var onGlobalPostMessage = function (event) {
1246 // Only if we're a match to avoid any other global events
1247 if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
1248 runTask(event.data.substring(MSG_PREFIX.length));
1249 }
1250 };
1251
1252 root.addEventListener('message', onGlobalPostMessage, false);
1253
1254 scheduleMethod = function (action) {
1255 var id = nextHandle++;
1256 tasksByHandle[id] = action;
1257 root.postMessage(MSG_PREFIX + currentId, '*');
1258 return id;
1259 };
1260 } else if (!!root.MessageChannel) {
1261 var channel = new root.MessageChannel();
1262
1263 channel.port1.onmessage = function (e) { runTask(e.data); };
1264
1265 scheduleMethod = function (action) {
1266 var id = nextHandle++;
1267 tasksByHandle[id] = action;
1268 channel.port2.postMessage(id);
1269 return id;
1270 };
1271 } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
1272
1273 scheduleMethod = function (action) {
1274 var scriptElement = root.document.createElement('script');
1275 var id = nextHandle++;
1276 tasksByHandle[id] = action;
1277
1278 scriptElement.onreadystatechange = function () {
1279 runTask(id);
1280 scriptElement.onreadystatechange = null;
1281 scriptElement.parentNode.removeChild(scriptElement);
1282 scriptElement = null;
1283 };
1284 root.document.documentElement.appendChild(scriptElement);
1285 return id;
1286 };
1287
1288 } else {
1289 scheduleMethod = function (action) {
1290 var id = nextHandle++;
1291 tasksByHandle[id] = action;
1292 localSetTimeout(function () {
1293 runTask(id);
1294 }, 0);
1295
1296 return id;
1297 };
1298 }
1299 }());
1300
1301 /**
1302 * Gets a scheduler that schedules work via a timed callback based upon platform.
1303 */
1304 var DefaultScheduler = (function (__super__) {
1305 inherits(DefaultScheduler, __super__);
1306 function DefaultScheduler() {
1307 __super__.call(this);
1308 }
1309
1310 function scheduleAction(disposable, action, scheduler, state) {
1311 return function schedule() {
1312 disposable.setDisposable(Disposable._fixup(action(scheduler, state)));
1313 };
1314 }
1315
1316 function ClearDisposable(id) {
1317 this._id = id;
1318 this.isDisposed = false;
1319 }
1320
1321 ClearDisposable.prototype.dispose = function () {
1322 if (!this.isDisposed) {
1323 this.isDisposed = true;
1324 clearMethod(this._id);
1325 }
1326 };
1327
1328 function LocalClearDisposable(id) {
1329 this._id = id;
1330 this.isDisposed = false;
1331 }
1332
1333 LocalClearDisposable.prototype.dispose = function () {
1334 if (!this.isDisposed) {
1335 this.isDisposed = true;
1336 localClearTimeout(this._id);
1337 }
1338 };
1339
1340 DefaultScheduler.prototype.schedule = function (state, action) {
1341 var disposable = new SingleAssignmentDisposable(),
1342 id = scheduleMethod(scheduleAction(disposable, action, this, state));
1343 return new BinaryDisposable(disposable, new ClearDisposable(id));
1344 };
1345
1346 DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
1347 if (dueTime === 0) { return this.schedule(state, action); }
1348 var disposable = new SingleAssignmentDisposable(),
1349 id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);
1350 return new BinaryDisposable(disposable, new LocalClearDisposable(id));
1351 };
1352
1353 return DefaultScheduler;
1354 }(Scheduler));
1355
1356 var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();
1357
1358 var CatchScheduler = (function (__super__) {
1359 inherits(CatchScheduler, __super__);
1360
1361 function CatchScheduler(scheduler, handler) {
1362 this._scheduler = scheduler;
1363 this._handler = handler;
1364 this._recursiveOriginal = null;
1365 this._recursiveWrapper = null;
1366 __super__.call(this);
1367 }
1368
1369 CatchScheduler.prototype.schedule = function (state, action) {
1370 return this._scheduler.schedule(state, this._wrap(action));
1371 };
1372
1373 CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
1374 return this._scheduler.schedule(state, dueTime, this._wrap(action));
1375 };
1376
1377 CatchScheduler.prototype.now = function () { return this._scheduler.now(); };
1378
1379 CatchScheduler.prototype._clone = function (scheduler) {
1380 return new CatchScheduler(scheduler, this._handler);
1381 };
1382
1383 CatchScheduler.prototype._wrap = function (action) {
1384 var parent = this;
1385 return function (self, state) {
1386 var res = tryCatch(action)(parent._getRecursiveWrapper(self), state);
1387 if (res === errorObj) {
1388 if (!parent._handler(res.e)) { thrower(res.e); }
1389 return disposableEmpty;
1390 }
1391 return disposableFixup(res);
1392 };
1393 };
1394
1395 CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
1396 if (this._recursiveOriginal !== scheduler) {
1397 this._recursiveOriginal = scheduler;
1398 var wrapper = this._clone(scheduler);
1399 wrapper._recursiveOriginal = scheduler;
1400 wrapper._recursiveWrapper = wrapper;
1401 this._recursiveWrapper = wrapper;
1402 }
1403 return this._recursiveWrapper;
1404 };
1405
1406 CatchScheduler.prototype.schedulePeriodic = function (state, period, action) {
1407 var self = this, failed = false, d = new SingleAssignmentDisposable();
1408
1409 d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) {
1410 if (failed) { return null; }
1411 var res = tryCatch(action)(state1);
1412 if (res === errorObj) {
1413 failed = true;
1414 if (!self._handler(res.e)) { thrower(res.e); }
1415 d.dispose();
1416 return null;
1417 }
1418 return res;
1419 }));
1420
1421 return d;
1422 };
1423
1424 return CatchScheduler;
1425 }(Scheduler));
1426
1427 function IndexedItem(id, value) {
1428 this.id = id;
1429 this.value = value;
1430 }
1431
1432 IndexedItem.prototype.compareTo = function (other) {
1433 var c = this.value.compareTo(other.value);
1434 c === 0 && (c = this.id - other.id);
1435 return c;
1436 };
1437
1438 var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
1439 this.items = new Array(capacity);
1440 this.length = 0;
1441 };
1442
1443 var priorityProto = PriorityQueue.prototype;
1444 priorityProto.isHigherPriority = function (left, right) {
1445 return this.items[left].compareTo(this.items[right]) < 0;
1446 };
1447
1448 priorityProto.percolate = function (index) {
1449 if (index >= this.length || index < 0) { return; }
1450 var parent = index - 1 >> 1;
1451 if (parent < 0 || parent === index) { return; }
1452 if (this.isHigherPriority(index, parent)) {
1453 var temp = this.items[index];
1454 this.items[index] = this.items[parent];
1455 this.items[parent] = temp;
1456 this.percolate(parent);
1457 }
1458 };
1459
1460 priorityProto.heapify = function (index) {
1461 +index || (index = 0);
1462 if (index >= this.length || index < 0) { return; }
1463 var left = 2 * index + 1,
1464 right = 2 * index + 2,
1465 first = index;
1466 if (left < this.length && this.isHigherPriority(left, first)) {
1467 first = left;
1468 }
1469 if (right < this.length && this.isHigherPriority(right, first)) {
1470 first = right;
1471 }
1472 if (first !== index) {
1473 var temp = this.items[index];
1474 this.items[index] = this.items[first];
1475 this.items[first] = temp;
1476 this.heapify(first);
1477 }
1478 };
1479
1480 priorityProto.peek = function () { return this.items[0].value; };
1481
1482 priorityProto.removeAt = function (index) {
1483 this.items[index] = this.items[--this.length];
1484 this.items[this.length] = undefined;
1485 this.heapify();
1486 };
1487
1488 priorityProto.dequeue = function () {
1489 var result = this.peek();
1490 this.removeAt(0);
1491 return result;
1492 };
1493
1494 priorityProto.enqueue = function (item) {
1495 var index = this.length++;
1496 this.items[index] = new IndexedItem(PriorityQueue.count++, item);
1497 this.percolate(index);
1498 };
1499
1500 priorityProto.remove = function (item) {
1501 for (var i = 0; i < this.length; i++) {
1502 if (this.items[i].value === item) {
1503 this.removeAt(i);
1504 return true;
1505 }
1506 }
1507 return false;
1508 };
1509 PriorityQueue.count = 0;
1510
1511 /**
1512 * Represents a notification to an observer.
1513 */
1514 var Notification = Rx.Notification = (function () {
1515 function Notification() {
1516
1517 }
1518
1519 Notification.prototype._accept = function (onNext, onError, onCompleted) {
1520 throw new NotImplementedError();
1521 };
1522
1523 Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
1524 throw new NotImplementedError();
1525 };
1526
1527 /**
1528 * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
1529 * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
1530 * @param {Function} onError Function to invoke for an OnError notification.
1531 * @param {Function} onCompleted Function to invoke for an OnCompleted notification.
1532 * @returns {Any} Result produced by the observation.
1533 */
1534 Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
1535 return observerOrOnNext && typeof observerOrOnNext === 'object' ?
1536 this._acceptObserver(observerOrOnNext) :
1537 this._accept(observerOrOnNext, onError, onCompleted);
1538 };
1539
1540 /**
1541 * Returns an observable sequence with a single notification.
1542 *
1543 * @memberOf Notifications
1544 * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
1545 * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
1546 */
1547 Notification.prototype.toObservable = function (scheduler) {
1548 var self = this;
1549 isScheduler(scheduler) || (scheduler = immediateScheduler);
1550 return new AnonymousObservable(function (o) {
1551 return scheduler.schedule(self, function (_, notification) {
1552 notification._acceptObserver(o);
1553 notification.kind === 'N' && o.onCompleted();
1554 });
1555 });
1556 };
1557
1558 return Notification;
1559 })();
1560
1561 var OnNextNotification = (function (__super__) {
1562 inherits(OnNextNotification, __super__);
1563 function OnNextNotification(value) {
1564 this.value = value;
1565 this.kind = 'N';
1566 }
1567
1568 OnNextNotification.prototype._accept = function (onNext) {
1569 return onNext(this.value);
1570 };
1571
1572 OnNextNotification.prototype._acceptObserver = function (o) {
1573 return o.onNext(this.value);
1574 };
1575
1576 OnNextNotification.prototype.toString = function () {
1577 return 'OnNext(' + this.value + ')';
1578 };
1579
1580 return OnNextNotification;
1581 }(Notification));
1582
1583 var OnErrorNotification = (function (__super__) {
1584 inherits(OnErrorNotification, __super__);
1585 function OnErrorNotification(error) {
1586 this.error = error;
1587 this.kind = 'E';
1588 }
1589
1590 OnErrorNotification.prototype._accept = function (onNext, onError) {
1591 return onError(this.error);
1592 };
1593
1594 OnErrorNotification.prototype._acceptObserver = function (o) {
1595 return o.onError(this.error);
1596 };
1597
1598 OnErrorNotification.prototype.toString = function () {
1599 return 'OnError(' + this.error + ')';
1600 };
1601
1602 return OnErrorNotification;
1603 }(Notification));
1604
1605 var OnCompletedNotification = (function (__super__) {
1606 inherits(OnCompletedNotification, __super__);
1607 function OnCompletedNotification() {
1608 this.kind = 'C';
1609 }
1610
1611 OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
1612 return onCompleted();
1613 };
1614
1615 OnCompletedNotification.prototype._acceptObserver = function (o) {
1616 return o.onCompleted();
1617 };
1618
1619 OnCompletedNotification.prototype.toString = function () {
1620 return 'OnCompleted()';
1621 };
1622
1623 return OnCompletedNotification;
1624 }(Notification));
1625
1626 /**
1627 * Creates an object that represents an OnNext notification to an observer.
1628 * @param {Any} value The value contained in the notification.
1629 * @returns {Notification} The OnNext notification containing the value.
1630 */
1631 var notificationCreateOnNext = Notification.createOnNext = function (value) {
1632 return new OnNextNotification(value);
1633 };
1634
1635 /**
1636 * Creates an object that represents an OnError notification to an observer.
1637 * @param {Any} error The exception contained in the notification.
1638 * @returns {Notification} The OnError notification containing the exception.
1639 */
1640 var notificationCreateOnError = Notification.createOnError = function (error) {
1641 return new OnErrorNotification(error);
1642 };
1643
1644 /**
1645 * Creates an object that represents an OnCompleted notification to an observer.
1646 * @returns {Notification} The OnCompleted notification.
1647 */
1648 var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
1649 return new OnCompletedNotification();
1650 };
1651
1652 /**
1653 * Supports push-style iteration over an observable sequence.
1654 */
1655 var Observer = Rx.Observer = function () { };
1656
1657 /**
1658 * Creates a notification callback from an observer.
1659 * @returns The action that forwards its input notification to the underlying observer.
1660 */
1661 Observer.prototype.toNotifier = function () {
1662 var observer = this;
1663 return function (n) { return n.accept(observer); };
1664 };
1665
1666 /**
1667 * Hides the identity of an observer.
1668 * @returns An observer that hides the identity of the specified observer.
1669 */
1670 Observer.prototype.asObserver = function () {
1671 var self = this;
1672 return new AnonymousObserver(
1673 function (x) { self.onNext(x); },
1674 function (err) { self.onError(err); },
1675 function () { self.onCompleted(); });
1676 };
1677
1678 /**
1679 * 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.
1680 * If a violation is detected, an Error is thrown from the offending observer method call.
1681 * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
1682 */
1683 Observer.prototype.checked = function () { return new CheckedObserver(this); };
1684
1685 /**
1686 * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
1687 * @param {Function} [onNext] Observer's OnNext action implementation.
1688 * @param {Function} [onError] Observer's OnError action implementation.
1689 * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
1690 * @returns {Observer} The observer object implemented using the given actions.
1691 */
1692 var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
1693 onNext || (onNext = noop);
1694 onError || (onError = defaultError);
1695 onCompleted || (onCompleted = noop);
1696 return new AnonymousObserver(onNext, onError, onCompleted);
1697 };
1698
1699 /**
1700 * Creates an observer from a notification callback.
1701 * @param {Function} handler Action that handles a notification.
1702 * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
1703 */
1704 Observer.fromNotifier = function (handler, thisArg) {
1705 var cb = bindCallback(handler, thisArg, 1);
1706 return new AnonymousObserver(function (x) {
1707 return cb(notificationCreateOnNext(x));
1708 }, function (e) {
1709 return cb(notificationCreateOnError(e));
1710 }, function () {
1711 return cb(notificationCreateOnCompleted());
1712 });
1713 };
1714
1715 /**
1716 * Schedules the invocation of observer methods on the given scheduler.
1717 * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
1718 * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
1719 */
1720 Observer.prototype.notifyOn = function (scheduler) {
1721 return new ObserveOnObserver(scheduler, this);
1722 };
1723
1724 Observer.prototype.makeSafe = function(disposable) {
1725 return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
1726 };
1727
1728 /**
1729 * Abstract base class for implementations of the Observer class.
1730 * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
1731 */
1732 var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
1733 inherits(AbstractObserver, __super__);
1734
1735 /**
1736 * Creates a new observer in a non-stopped state.
1737 */
1738 function AbstractObserver() {
1739 this.isStopped = false;
1740 }
1741
1742 // Must be implemented by other observers
1743 AbstractObserver.prototype.next = notImplemented;
1744 AbstractObserver.prototype.error = notImplemented;
1745 AbstractObserver.prototype.completed = notImplemented;
1746
1747 /**
1748 * Notifies the observer of a new element in the sequence.
1749 * @param {Any} value Next element in the sequence.
1750 */
1751 AbstractObserver.prototype.onNext = function (value) {
1752 !this.isStopped && this.next(value);
1753 };
1754
1755 /**
1756 * Notifies the observer that an exception has occurred.
1757 * @param {Any} error The error that has occurred.
1758 */
1759 AbstractObserver.prototype.onError = function (error) {
1760 if (!this.isStopped) {
1761 this.isStopped = true;
1762 this.error(error);
1763 }
1764 };
1765
1766 /**
1767 * Notifies the observer of the end of the sequence.
1768 */
1769 AbstractObserver.prototype.onCompleted = function () {
1770 if (!this.isStopped) {
1771 this.isStopped = true;
1772 this.completed();
1773 }
1774 };
1775
1776 /**
1777 * Disposes the observer, causing it to transition to the stopped state.
1778 */
1779 AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
1780
1781 AbstractObserver.prototype.fail = function (e) {
1782 if (!this.isStopped) {
1783 this.isStopped = true;
1784 this.error(e);
1785 return true;
1786 }
1787
1788 return false;
1789 };
1790
1791 return AbstractObserver;
1792 }(Observer));
1793
1794 /**
1795 * Class to create an Observer instance from delegate-based implementations of the on* methods.
1796 */
1797 var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
1798 inherits(AnonymousObserver, __super__);
1799
1800 /**
1801 * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
1802 * @param {Any} onNext Observer's OnNext action implementation.
1803 * @param {Any} onError Observer's OnError action implementation.
1804 * @param {Any} onCompleted Observer's OnCompleted action implementation.
1805 */
1806 function AnonymousObserver(onNext, onError, onCompleted) {
1807 __super__.call(this);
1808 this._onNext = onNext;
1809 this._onError = onError;
1810 this._onCompleted = onCompleted;
1811 }
1812
1813 /**
1814 * Calls the onNext action.
1815 * @param {Any} value Next element in the sequence.
1816 */
1817 AnonymousObserver.prototype.next = function (value) {
1818 this._onNext(value);
1819 };
1820
1821 /**
1822 * Calls the onError action.
1823 * @param {Any} error The error that has occurred.
1824 */
1825 AnonymousObserver.prototype.error = function (error) {
1826 this._onError(error);
1827 };
1828
1829 /**
1830 * Calls the onCompleted action.
1831 */
1832 AnonymousObserver.prototype.completed = function () {
1833 this._onCompleted();
1834 };
1835
1836 return AnonymousObserver;
1837 }(AbstractObserver));
1838
1839 var CheckedObserver = (function (__super__) {
1840 inherits(CheckedObserver, __super__);
1841
1842 function CheckedObserver(observer) {
1843 __super__.call(this);
1844 this._observer = observer;
1845 this._state = 0; // 0 - idle, 1 - busy, 2 - done
1846 }
1847
1848 var CheckedObserverPrototype = CheckedObserver.prototype;
1849
1850 CheckedObserverPrototype.onNext = function (value) {
1851 this.checkAccess();
1852 var res = tryCatch(this._observer.onNext).call(this._observer, value);
1853 this._state = 0;
1854 res === errorObj && thrower(res.e);
1855 };
1856
1857 CheckedObserverPrototype.onError = function (err) {
1858 this.checkAccess();
1859 var res = tryCatch(this._observer.onError).call(this._observer, err);
1860 this._state = 2;
1861 res === errorObj && thrower(res.e);
1862 };
1863
1864 CheckedObserverPrototype.onCompleted = function () {
1865 this.checkAccess();
1866 var res = tryCatch(this._observer.onCompleted).call(this._observer);
1867 this._state = 2;
1868 res === errorObj && thrower(res.e);
1869 };
1870
1871 CheckedObserverPrototype.checkAccess = function () {
1872 if (this._state === 1) { throw new Error('Re-entrancy detected'); }
1873 if (this._state === 2) { throw new Error('Observer completed'); }
1874 if (this._state === 0) { this._state = 1; }
1875 };
1876
1877 return CheckedObserver;
1878 }(Observer));
1879
1880 var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
1881 inherits(ScheduledObserver, __super__);
1882
1883 function ScheduledObserver(scheduler, observer) {
1884 __super__.call(this);
1885 this.scheduler = scheduler;
1886 this.observer = observer;
1887 this.isAcquired = false;
1888 this.hasFaulted = false;
1889 this.queue = [];
1890 this.disposable = new SerialDisposable();
1891 }
1892
1893 function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }
1894 function enqueueError(observer, e) { return function () { observer.onError(e); }; }
1895 function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }
1896
1897 ScheduledObserver.prototype.next = function (x) {
1898 this.queue.push(enqueueNext(this.observer, x));
1899 };
1900
1901 ScheduledObserver.prototype.error = function (e) {
1902 this.queue.push(enqueueError(this.observer, e));
1903 };
1904
1905 ScheduledObserver.prototype.completed = function () {
1906 this.queue.push(enqueueCompleted(this.observer));
1907 };
1908
1909
1910 function scheduleMethod(state, recurse) {
1911 var work;
1912 if (state.queue.length > 0) {
1913 work = state.queue.shift();
1914 } else {
1915 state.isAcquired = false;
1916 return;
1917 }
1918 var res = tryCatch(work)();
1919 if (res === errorObj) {
1920 state.queue = [];
1921 state.hasFaulted = true;
1922 return thrower(res.e);
1923 }
1924 recurse(state);
1925 }
1926
1927 ScheduledObserver.prototype.ensureActive = function () {
1928 var isOwner = false;
1929 if (!this.hasFaulted && this.queue.length > 0) {
1930 isOwner = !this.isAcquired;
1931 this.isAcquired = true;
1932 }
1933 isOwner &&
1934 this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));
1935 };
1936
1937 ScheduledObserver.prototype.dispose = function () {
1938 __super__.prototype.dispose.call(this);
1939 this.disposable.dispose();
1940 };
1941
1942 return ScheduledObserver;
1943 }(AbstractObserver));
1944
1945 var ObserveOnObserver = (function (__super__) {
1946 inherits(ObserveOnObserver, __super__);
1947
1948 function ObserveOnObserver(scheduler, observer, cancel) {
1949 __super__.call(this, scheduler, observer);
1950 this._cancel = cancel;
1951 }
1952
1953 ObserveOnObserver.prototype.next = function (value) {
1954 __super__.prototype.next.call(this, value);
1955 this.ensureActive();
1956 };
1957
1958 ObserveOnObserver.prototype.error = function (e) {
1959 __super__.prototype.error.call(this, e);
1960 this.ensureActive();
1961 };
1962
1963 ObserveOnObserver.prototype.completed = function () {
1964 __super__.prototype.completed.call(this);
1965 this.ensureActive();
1966 };
1967
1968 ObserveOnObserver.prototype.dispose = function () {
1969 __super__.prototype.dispose.call(this);
1970 this._cancel && this._cancel.dispose();
1971 this._cancel = null;
1972 };
1973
1974 return ObserveOnObserver;
1975 })(ScheduledObserver);
1976
1977 var observableProto;
1978
1979 /**
1980 * Represents a push-style collection.
1981 */
1982 var Observable = Rx.Observable = (function () {
1983
1984 function makeSubscribe(self, subscribe) {
1985 return function (o) {
1986 var oldOnError = o.onError;
1987 o.onError = function (e) {
1988 makeStackTraceLong(e, self);
1989 oldOnError.call(o, e);
1990 };
1991
1992 return subscribe.call(self, o);
1993 };
1994 }
1995
1996 function Observable() {
1997 if (Rx.config.longStackSupport && hasStacks) {
1998 var oldSubscribe = this._subscribe;
1999 var e = tryCatch(thrower)(new Error()).e;
2000 this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
2001 this._subscribe = makeSubscribe(this, oldSubscribe);
2002 }
2003 }
2004
2005 observableProto = Observable.prototype;
2006
2007 /**
2008 * Determines whether the given object is an Observable
2009 * @param {Any} An object to determine whether it is an Observable
2010 * @returns {Boolean} true if an Observable, else false.
2011 */
2012 Observable.isObservable = function (o) {
2013 return o && isFunction(o.subscribe);
2014 };
2015
2016 /**
2017 * Subscribes an o to the observable sequence.
2018 * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
2019 * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
2020 * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
2021 * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
2022 */
2023 observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
2024 return this._subscribe(typeof oOrOnNext === 'object' ?
2025 oOrOnNext :
2026 observerCreate(oOrOnNext, onError, onCompleted));
2027 };
2028
2029 /**
2030 * Subscribes to the next value in the sequence with an optional "this" argument.
2031 * @param {Function} onNext The function to invoke on each element in the observable sequence.
2032 * @param {Any} [thisArg] Object to use as this when executing callback.
2033 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2034 */
2035 observableProto.subscribeOnNext = function (onNext, thisArg) {
2036 return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
2037 };
2038
2039 /**
2040 * Subscribes to an exceptional condition in the sequence with an optional "this" argument.
2041 * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
2042 * @param {Any} [thisArg] Object to use as this when executing callback.
2043 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2044 */
2045 observableProto.subscribeOnError = function (onError, thisArg) {
2046 return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
2047 };
2048
2049 /**
2050 * Subscribes to the next value in the sequence with an optional "this" argument.
2051 * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
2052 * @param {Any} [thisArg] Object to use as this when executing callback.
2053 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2054 */
2055 observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
2056 return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
2057 };
2058
2059 return Observable;
2060 })();
2061
2062 var ObservableBase = Rx.ObservableBase = (function (__super__) {
2063 inherits(ObservableBase, __super__);
2064
2065 function fixSubscriber(subscriber) {
2066 return subscriber && isFunction(subscriber.dispose) ? subscriber :
2067 isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
2068 }
2069
2070 function setDisposable(s, state) {
2071 var ado = state[0], self = state[1];
2072 var sub = tryCatch(self.subscribeCore).call(self, ado);
2073 if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
2074 ado.setDisposable(fixSubscriber(sub));
2075 }
2076
2077 function ObservableBase() {
2078 __super__.call(this);
2079 }
2080
2081 ObservableBase.prototype._subscribe = function (o) {
2082 var ado = new AutoDetachObserver(o), state = [ado, this];
2083
2084 if (currentThreadScheduler.scheduleRequired()) {
2085 currentThreadScheduler.schedule(state, setDisposable);
2086 } else {
2087 setDisposable(null, state);
2088 }
2089 return ado;
2090 };
2091
2092 ObservableBase.prototype.subscribeCore = notImplemented;
2093
2094 return ObservableBase;
2095 }(Observable));
2096
2097var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {
2098
2099 inherits(FlatMapObservable, __super__);
2100
2101 function FlatMapObservable(source, selector, resultSelector, thisArg) {
2102 this.resultSelector = isFunction(resultSelector) ? resultSelector : null;
2103 this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
2104 this.source = source;
2105 __super__.call(this);
2106 }
2107
2108 FlatMapObservable.prototype.subscribeCore = function(o) {
2109 return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
2110 };
2111
2112 inherits(InnerObserver, AbstractObserver);
2113 function InnerObserver(observer, selector, resultSelector, source) {
2114 this.i = 0;
2115 this.selector = selector;
2116 this.resultSelector = resultSelector;
2117 this.source = source;
2118 this.o = observer;
2119 AbstractObserver.call(this);
2120 }
2121
2122 InnerObserver.prototype._wrapResult = function(result, x, i) {
2123 return this.resultSelector ?
2124 result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
2125 result;
2126 };
2127
2128 InnerObserver.prototype.next = function(x) {
2129 var i = this.i++;
2130 var result = tryCatch(this.selector)(x, i, this.source);
2131 if (result === errorObj) { return this.o.onError(result.e); }
2132
2133 isPromise(result) && (result = observableFromPromise(result));
2134 (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));
2135 this.o.onNext(this._wrapResult(result, x, i));
2136 };
2137
2138 InnerObserver.prototype.error = function(e) { this.o.onError(e); };
2139
2140 InnerObserver.prototype.completed = function() { this.o.onCompleted(); };
2141
2142 return FlatMapObservable;
2143
2144}(ObservableBase));
2145
2146 var Enumerable = Rx.internals.Enumerable = function () { };
2147
2148 function IsDisposedDisposable(state) {
2149 this._s = state;
2150 this.isDisposed = false;
2151 }
2152
2153 IsDisposedDisposable.prototype.dispose = function () {
2154 if (!this.isDisposed) {
2155 this.isDisposed = true;
2156 this._s.isDisposed = true;
2157 }
2158 };
2159
2160 var ConcatEnumerableObservable = (function(__super__) {
2161 inherits(ConcatEnumerableObservable, __super__);
2162 function ConcatEnumerableObservable(sources) {
2163 this.sources = sources;
2164 __super__.call(this);
2165 }
2166
2167 function scheduleMethod(state, recurse) {
2168 if (state.isDisposed) { return; }
2169 var currentItem = tryCatch(state.e.next).call(state.e);
2170 if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
2171 if (currentItem.done) { return state.o.onCompleted(); }
2172
2173 // Check if promise
2174 var currentValue = currentItem.value;
2175 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2176
2177 var d = new SingleAssignmentDisposable();
2178 state.subscription.setDisposable(d);
2179 d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
2180 }
2181
2182 ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
2183 var subscription = new SerialDisposable();
2184 var state = {
2185 isDisposed: false,
2186 o: o,
2187 subscription: subscription,
2188 e: this.sources[$iterator$]()
2189 };
2190
2191 var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
2192 return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
2193 };
2194
2195 function InnerObserver(state, recurse) {
2196 this._state = state;
2197 this._recurse = recurse;
2198 AbstractObserver.call(this);
2199 }
2200
2201 inherits(InnerObserver, AbstractObserver);
2202
2203 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
2204 InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };
2205 InnerObserver.prototype.completed = function () { this._recurse(this._state); };
2206
2207 return ConcatEnumerableObservable;
2208 }(ObservableBase));
2209
2210 Enumerable.prototype.concat = function () {
2211 return new ConcatEnumerableObservable(this);
2212 };
2213
2214 var CatchErrorObservable = (function(__super__) {
2215 function CatchErrorObservable(sources) {
2216 this.sources = sources;
2217 __super__.call(this);
2218 }
2219
2220 inherits(CatchErrorObservable, __super__);
2221
2222 function scheduleMethod(state, recurse) {
2223 if (state.isDisposed) { return; }
2224 var currentItem = tryCatch(state.e.next).call(state.e);
2225 if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
2226 if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }
2227
2228 var currentValue = currentItem.value;
2229 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2230
2231 var d = new SingleAssignmentDisposable();
2232 state.subscription.setDisposable(d);
2233 d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
2234 }
2235
2236 CatchErrorObservable.prototype.subscribeCore = function (o) {
2237 var subscription = new SerialDisposable();
2238 var state = {
2239 isDisposed: false,
2240 e: this.sources[$iterator$](),
2241 subscription: subscription,
2242 lastError: null,
2243 o: o
2244 };
2245
2246 var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
2247 return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
2248 };
2249
2250 function InnerObserver(state, recurse) {
2251 this._state = state;
2252 this._recurse = recurse;
2253 AbstractObserver.call(this);
2254 }
2255
2256 inherits(InnerObserver, AbstractObserver);
2257
2258 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
2259 InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };
2260 InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };
2261
2262 return CatchErrorObservable;
2263 }(ObservableBase));
2264
2265 Enumerable.prototype.catchError = function () {
2266 return new CatchErrorObservable(this);
2267 };
2268
2269 Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
2270 var sources = this;
2271 return new AnonymousObservable(function (o) {
2272 var exceptions = new Subject(),
2273 notifier = new Subject(),
2274 handled = notificationHandler(exceptions),
2275 notificationDisposable = handled.subscribe(notifier);
2276
2277 var e = sources[$iterator$]();
2278
2279 var state = { isDisposed: false },
2280 lastError,
2281 subscription = new SerialDisposable();
2282 var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, self) {
2283 if (state.isDisposed) { return; }
2284 var currentItem = tryCatch(e.next).call(e);
2285 if (currentItem === errorObj) { return o.onError(currentItem.e); }
2286
2287 if (currentItem.done) {
2288 if (lastError) {
2289 o.onError(lastError);
2290 } else {
2291 o.onCompleted();
2292 }
2293 return;
2294 }
2295
2296 // Check if promise
2297 var currentValue = currentItem.value;
2298 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2299
2300 var outer = new SingleAssignmentDisposable();
2301 var inner = new SingleAssignmentDisposable();
2302 subscription.setDisposable(new BinaryDisposable(inner, outer));
2303 outer.setDisposable(currentValue.subscribe(
2304 function(x) { o.onNext(x); },
2305 function (exn) {
2306 inner.setDisposable(notifier.subscribe(self, function(ex) {
2307 o.onError(ex);
2308 }, function() {
2309 o.onCompleted();
2310 }));
2311
2312 exceptions.onNext(exn);
2313 },
2314 function() { o.onCompleted(); }));
2315 });
2316
2317 return new NAryDisposable([notificationDisposable, subscription, cancelable, new IsDisposedDisposable(state)]);
2318 });
2319 };
2320
2321 var RepeatEnumerable = (function (__super__) {
2322 inherits(RepeatEnumerable, __super__);
2323 function RepeatEnumerable(v, c) {
2324 this.v = v;
2325 this.c = c == null ? -1 : c;
2326 }
2327
2328 RepeatEnumerable.prototype[$iterator$] = function () {
2329 return new RepeatEnumerator(this);
2330 };
2331
2332 function RepeatEnumerator(p) {
2333 this.v = p.v;
2334 this.l = p.c;
2335 }
2336
2337 RepeatEnumerator.prototype.next = function () {
2338 if (this.l === 0) { return doneEnumerator; }
2339 if (this.l > 0) { this.l--; }
2340 return { done: false, value: this.v };
2341 };
2342
2343 return RepeatEnumerable;
2344 }(Enumerable));
2345
2346 var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
2347 return new RepeatEnumerable(value, repeatCount);
2348 };
2349
2350 var OfEnumerable = (function(__super__) {
2351 inherits(OfEnumerable, __super__);
2352 function OfEnumerable(s, fn, thisArg) {
2353 this.s = s;
2354 this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
2355 }
2356 OfEnumerable.prototype[$iterator$] = function () {
2357 return new OfEnumerator(this);
2358 };
2359
2360 function OfEnumerator(p) {
2361 this.i = -1;
2362 this.s = p.s;
2363 this.l = this.s.length;
2364 this.fn = p.fn;
2365 }
2366
2367 OfEnumerator.prototype.next = function () {
2368 return ++this.i < this.l ?
2369 { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
2370 doneEnumerator;
2371 };
2372
2373 return OfEnumerable;
2374 }(Enumerable));
2375
2376 var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
2377 return new OfEnumerable(source, selector, thisArg);
2378 };
2379
2380var ObserveOnObservable = (function (__super__) {
2381 inherits(ObserveOnObservable, __super__);
2382 function ObserveOnObservable(source, s) {
2383 this.source = source;
2384 this._s = s;
2385 __super__.call(this);
2386 }
2387
2388 ObserveOnObservable.prototype.subscribeCore = function (o) {
2389 return this.source.subscribe(new ObserveOnObserver(this._s, o));
2390 };
2391
2392 return ObserveOnObservable;
2393}(ObservableBase));
2394
2395 /**
2396 * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
2397 *
2398 * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
2399 * that require to be run on a scheduler, use subscribeOn.
2400 *
2401 * @param {Scheduler} scheduler Scheduler to notify observers on.
2402 * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
2403 */
2404 observableProto.observeOn = function (scheduler) {
2405 return new ObserveOnObservable(this, scheduler);
2406 };
2407
2408 var SubscribeOnObservable = (function (__super__) {
2409 inherits(SubscribeOnObservable, __super__);
2410 function SubscribeOnObservable(source, s) {
2411 this.source = source;
2412 this._s = s;
2413 __super__.call(this);
2414 }
2415
2416 function scheduleMethod(scheduler, state) {
2417 var source = state[0], d = state[1], o = state[2];
2418 d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
2419 }
2420
2421 SubscribeOnObservable.prototype.subscribeCore = function (o) {
2422 var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
2423 d.setDisposable(m);
2424 m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
2425 return d;
2426 };
2427
2428 return SubscribeOnObservable;
2429 }(ObservableBase));
2430
2431 /**
2432 * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
2433 * see the remarks section for more information on the distinction between subscribeOn and observeOn.
2434
2435 * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
2436 * callbacks on a scheduler, use observeOn.
2437
2438 * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
2439 * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
2440 */
2441 observableProto.subscribeOn = function (scheduler) {
2442 return new SubscribeOnObservable(this, scheduler);
2443 };
2444
2445 var FromPromiseObservable = (function(__super__) {
2446 inherits(FromPromiseObservable, __super__);
2447 function FromPromiseObservable(p, s) {
2448 this._p = p;
2449 this._s = s;
2450 __super__.call(this);
2451 }
2452
2453 function scheduleNext(s, state) {
2454 var o = state[0], data = state[1];
2455 o.onNext(data);
2456 o.onCompleted();
2457 }
2458
2459 function scheduleError(s, state) {
2460 var o = state[0], err = state[1];
2461 o.onError(err);
2462 }
2463
2464 FromPromiseObservable.prototype.subscribeCore = function(o) {
2465 var sad = new SingleAssignmentDisposable(), self = this;
2466
2467 this._p
2468 .then(function (data) {
2469 sad.setDisposable(self._s.schedule([o, data], scheduleNext));
2470 }, function (err) {
2471 sad.setDisposable(self._s.schedule([o, err], scheduleError));
2472 });
2473
2474 return sad;
2475 };
2476
2477 return FromPromiseObservable;
2478 }(ObservableBase));
2479
2480 /**
2481 * Converts a Promise to an Observable sequence
2482 * @param {Promise} An ES6 Compliant promise.
2483 * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
2484 */
2485 var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {
2486 scheduler || (scheduler = defaultScheduler);
2487 return new FromPromiseObservable(promise, scheduler);
2488 };
2489
2490 /*
2491 * Converts an existing observable sequence to an ES6 Compatible Promise
2492 * @example
2493 * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
2494 *
2495 * // With config
2496 * Rx.config.Promise = RSVP.Promise;
2497 * var promise = Rx.Observable.return(42).toPromise();
2498 * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
2499 * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
2500 */
2501 observableProto.toPromise = function (promiseCtor) {
2502 promiseCtor || (promiseCtor = Rx.config.Promise);
2503 if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
2504 var source = this;
2505 return new promiseCtor(function (resolve, reject) {
2506 // No cancellation can be done
2507 var value;
2508 source.subscribe(function (v) {
2509 value = v;
2510 }, reject, function () {
2511 resolve(value);
2512 });
2513 });
2514 };
2515
2516 var ToArrayObservable = (function(__super__) {
2517 inherits(ToArrayObservable, __super__);
2518 function ToArrayObservable(source) {
2519 this.source = source;
2520 __super__.call(this);
2521 }
2522
2523 ToArrayObservable.prototype.subscribeCore = function(o) {
2524 return this.source.subscribe(new InnerObserver(o));
2525 };
2526
2527 inherits(InnerObserver, AbstractObserver);
2528 function InnerObserver(o) {
2529 this.o = o;
2530 this.a = [];
2531 AbstractObserver.call(this);
2532 }
2533
2534 InnerObserver.prototype.next = function (x) { this.a.push(x); };
2535 InnerObserver.prototype.error = function (e) { this.o.onError(e); };
2536 InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };
2537
2538 return ToArrayObservable;
2539 }(ObservableBase));
2540
2541 /**
2542 * Creates an array from an observable sequence.
2543 * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
2544 */
2545 observableProto.toArray = function () {
2546 return new ToArrayObservable(this);
2547 };
2548
2549 /**
2550 * Creates an observable sequence from a specified subscribe method implementation.
2551 * @example
2552 * var res = Rx.Observable.create(function (observer) { return function () { } );
2553 * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
2554 * var res = Rx.Observable.create(function (observer) { } );
2555 * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
2556 * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
2557 */
2558 Observable.create = function (subscribe, parent) {
2559 return new AnonymousObservable(subscribe, parent);
2560 };
2561
2562 var Defer = (function(__super__) {
2563 inherits(Defer, __super__);
2564 function Defer(factory) {
2565 this._f = factory;
2566 __super__.call(this);
2567 }
2568
2569 Defer.prototype.subscribeCore = function (o) {
2570 var result = tryCatch(this._f)();
2571 if (result === errorObj) { return observableThrow(result.e).subscribe(o);}
2572 isPromise(result) && (result = observableFromPromise(result));
2573 return result.subscribe(o);
2574 };
2575
2576 return Defer;
2577 }(ObservableBase));
2578
2579 /**
2580 * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
2581 *
2582 * @example
2583 * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
2584 * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
2585 * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
2586 */
2587 var observableDefer = Observable.defer = function (observableFactory) {
2588 return new Defer(observableFactory);
2589 };
2590
2591 var EmptyObservable = (function(__super__) {
2592 inherits(EmptyObservable, __super__);
2593 function EmptyObservable(scheduler) {
2594 this.scheduler = scheduler;
2595 __super__.call(this);
2596 }
2597
2598 EmptyObservable.prototype.subscribeCore = function (observer) {
2599 var sink = new EmptySink(observer, this.scheduler);
2600 return sink.run();
2601 };
2602
2603 function EmptySink(observer, scheduler) {
2604 this.observer = observer;
2605 this.scheduler = scheduler;
2606 }
2607
2608 function scheduleItem(s, state) {
2609 state.onCompleted();
2610 return disposableEmpty;
2611 }
2612
2613 EmptySink.prototype.run = function () {
2614 var state = this.observer;
2615 return this.scheduler === immediateScheduler ?
2616 scheduleItem(null, state) :
2617 this.scheduler.schedule(state, scheduleItem);
2618 };
2619
2620 return EmptyObservable;
2621 }(ObservableBase));
2622
2623 var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
2624
2625 /**
2626 * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
2627 *
2628 * @example
2629 * var res = Rx.Observable.empty();
2630 * var res = Rx.Observable.empty(Rx.Scheduler.timeout);
2631 * @param {Scheduler} [scheduler] Scheduler to send the termination call on.
2632 * @returns {Observable} An observable sequence with no elements.
2633 */
2634 var observableEmpty = Observable.empty = function (scheduler) {
2635 isScheduler(scheduler) || (scheduler = immediateScheduler);
2636 return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
2637 };
2638
2639 var FromObservable = (function(__super__) {
2640 inherits(FromObservable, __super__);
2641 function FromObservable(iterable, fn, scheduler) {
2642 this._iterable = iterable;
2643 this._fn = fn;
2644 this._scheduler = scheduler;
2645 __super__.call(this);
2646 }
2647
2648 function createScheduleMethod(o, it, fn) {
2649 return function loopRecursive(i, recurse) {
2650 var next = tryCatch(it.next).call(it);
2651 if (next === errorObj) { return o.onError(next.e); }
2652 if (next.done) { return o.onCompleted(); }
2653
2654 var result = next.value;
2655
2656 if (isFunction(fn)) {
2657 result = tryCatch(fn)(result, i);
2658 if (result === errorObj) { return o.onError(result.e); }
2659 }
2660
2661 o.onNext(result);
2662 recurse(i + 1);
2663 };
2664 }
2665
2666 FromObservable.prototype.subscribeCore = function (o) {
2667 var list = Object(this._iterable),
2668 it = getIterable(list);
2669
2670 return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));
2671 };
2672
2673 return FromObservable;
2674 }(ObservableBase));
2675
2676 var maxSafeInteger = Math.pow(2, 53) - 1;
2677
2678 function StringIterable(s) {
2679 this._s = s;
2680 }
2681
2682 StringIterable.prototype[$iterator$] = function () {
2683 return new StringIterator(this._s);
2684 };
2685
2686 function StringIterator(s) {
2687 this._s = s;
2688 this._l = s.length;
2689 this._i = 0;
2690 }
2691
2692 StringIterator.prototype[$iterator$] = function () {
2693 return this;
2694 };
2695
2696 StringIterator.prototype.next = function () {
2697 return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
2698 };
2699
2700 function ArrayIterable(a) {
2701 this._a = a;
2702 }
2703
2704 ArrayIterable.prototype[$iterator$] = function () {
2705 return new ArrayIterator(this._a);
2706 };
2707
2708 function ArrayIterator(a) {
2709 this._a = a;
2710 this._l = toLength(a);
2711 this._i = 0;
2712 }
2713
2714 ArrayIterator.prototype[$iterator$] = function () {
2715 return this;
2716 };
2717
2718 ArrayIterator.prototype.next = function () {
2719 return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
2720 };
2721
2722 function numberIsFinite(value) {
2723 return typeof value === 'number' && root.isFinite(value);
2724 }
2725
2726 function isNan(n) {
2727 return n !== n;
2728 }
2729
2730 function getIterable(o) {
2731 var i = o[$iterator$], it;
2732 if (!i && typeof o === 'string') {
2733 it = new StringIterable(o);
2734 return it[$iterator$]();
2735 }
2736 if (!i && o.length !== undefined) {
2737 it = new ArrayIterable(o);
2738 return it[$iterator$]();
2739 }
2740 if (!i) { throw new TypeError('Object is not iterable'); }
2741 return o[$iterator$]();
2742 }
2743
2744 function sign(value) {
2745 var number = +value;
2746 if (number === 0) { return number; }
2747 if (isNaN(number)) { return number; }
2748 return number < 0 ? -1 : 1;
2749 }
2750
2751 function toLength(o) {
2752 var len = +o.length;
2753 if (isNaN(len)) { return 0; }
2754 if (len === 0 || !numberIsFinite(len)) { return len; }
2755 len = sign(len) * Math.floor(Math.abs(len));
2756 if (len <= 0) { return 0; }
2757 if (len > maxSafeInteger) { return maxSafeInteger; }
2758 return len;
2759 }
2760
2761 /**
2762 * This method creates a new Observable sequence from an array-like or iterable object.
2763 * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
2764 * @param {Function} [mapFn] Map function to call on every element of the array.
2765 * @param {Any} [thisArg] The context to use calling the mapFn if provided.
2766 * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
2767 */
2768 var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
2769 if (iterable == null) {
2770 throw new Error('iterable cannot be null.')
2771 }
2772 if (mapFn && !isFunction(mapFn)) {
2773 throw new Error('mapFn when provided must be a function');
2774 }
2775 if (mapFn) {
2776 var mapper = bindCallback(mapFn, thisArg, 2);
2777 }
2778 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
2779 return new FromObservable(iterable, mapper, scheduler);
2780 }
2781
2782 var FromArrayObservable = (function(__super__) {
2783 inherits(FromArrayObservable, __super__);
2784 function FromArrayObservable(args, scheduler) {
2785 this._args = args;
2786 this._scheduler = scheduler;
2787 __super__.call(this);
2788 }
2789
2790 function scheduleMethod(o, args) {
2791 var len = args.length;
2792 return function loopRecursive (i, recurse) {
2793 if (i < len) {
2794 o.onNext(args[i]);
2795 recurse(i + 1);
2796 } else {
2797 o.onCompleted();
2798 }
2799 };
2800 }
2801
2802 FromArrayObservable.prototype.subscribeCore = function (o) {
2803 return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));
2804 };
2805
2806 return FromArrayObservable;
2807 }(ObservableBase));
2808
2809 /**
2810 * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
2811 * @deprecated use Observable.from or Observable.of
2812 * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
2813 * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
2814 */
2815 var observableFromArray = Observable.fromArray = function (array, scheduler) {
2816 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
2817 return new FromArrayObservable(array, scheduler)
2818 };
2819
2820 var GenerateObservable = (function (__super__) {
2821 inherits(GenerateObservable, __super__);
2822 function GenerateObservable(state, cndFn, itrFn, resFn, s) {
2823 this._state = state;
2824 this._cndFn = cndFn;
2825 this._itrFn = itrFn;
2826 this._resFn = resFn;
2827 this._s = s;
2828 this._first = true;
2829 __super__.call(this);
2830 }
2831
2832 function scheduleRecursive(self, recurse) {
2833 if (self._first) {
2834 self._first = false;
2835 } else {
2836 self._state = tryCatch(self._itrFn)(self._state);
2837 if (self._state === errorObj) { return self._o.onError(self._state.e); }
2838 }
2839 var hasResult = tryCatch(self._cndFn)(self._state);
2840 if (hasResult === errorObj) { return self._o.onError(hasResult.e); }
2841 if (hasResult) {
2842 var result = tryCatch(self._resFn)(self._state);
2843 if (result === errorObj) { return self._o.onError(result.e); }
2844 self._o.onNext(result);
2845 recurse(self);
2846 } else {
2847 self._o.onCompleted();
2848 }
2849 }
2850
2851 GenerateObservable.prototype.subscribeCore = function (o) {
2852 this._o = o;
2853 return this._s.scheduleRecursive(this, scheduleRecursive);
2854 };
2855
2856 return GenerateObservable;
2857 }(ObservableBase));
2858
2859 /**
2860 * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
2861 *
2862 * @example
2863 * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
2864 * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
2865 * @param {Mixed} initialState Initial state.
2866 * @param {Function} condition Condition to terminate generation (upon returning false).
2867 * @param {Function} iterate Iteration step function.
2868 * @param {Function} resultSelector Selector function for results produced in the sequence.
2869 * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
2870 * @returns {Observable} The generated sequence.
2871 */
2872 Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
2873 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
2874 return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
2875 };
2876
2877 var NeverObservable = (function(__super__) {
2878 inherits(NeverObservable, __super__);
2879 function NeverObservable() {
2880 __super__.call(this);
2881 }
2882
2883 NeverObservable.prototype.subscribeCore = function (observer) {
2884 return disposableEmpty;
2885 };
2886
2887 return NeverObservable;
2888 }(ObservableBase));
2889
2890 var NEVER_OBSERVABLE = new NeverObservable();
2891
2892 /**
2893 * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
2894 * @returns {Observable} An observable sequence whose observers will never get called.
2895 */
2896 var observableNever = Observable.never = function () {
2897 return NEVER_OBSERVABLE;
2898 };
2899
2900 function observableOf (scheduler, array) {
2901 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
2902 return new FromArrayObservable(array, scheduler);
2903 }
2904
2905 /**
2906 * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
2907 * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
2908 */
2909 Observable.of = function () {
2910 var len = arguments.length, args = new Array(len);
2911 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
2912 return new FromArrayObservable(args, currentThreadScheduler);
2913 };
2914
2915 /**
2916 * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
2917 * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
2918 * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
2919 */
2920 Observable.ofWithScheduler = function (scheduler) {
2921 var len = arguments.length, args = new Array(len - 1);
2922 for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
2923 return new FromArrayObservable(args, scheduler);
2924 };
2925
2926 var PairsObservable = (function(__super__) {
2927 inherits(PairsObservable, __super__);
2928 function PairsObservable(o, scheduler) {
2929 this._o = o;
2930 this._keys = Object.keys(o);
2931 this._scheduler = scheduler;
2932 __super__.call(this);
2933 }
2934
2935 function scheduleMethod(o, obj, keys) {
2936 return function loopRecursive(i, recurse) {
2937 if (i < keys.length) {
2938 var key = keys[i];
2939 o.onNext([key, obj[key]]);
2940 recurse(i + 1);
2941 } else {
2942 o.onCompleted();
2943 }
2944 };
2945 }
2946
2947 PairsObservable.prototype.subscribeCore = function (o) {
2948 return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));
2949 };
2950
2951 return PairsObservable;
2952 }(ObservableBase));
2953
2954 /**
2955 * Convert an object into an observable sequence of [key, value] pairs.
2956 * @param {Object} obj The object to inspect.
2957 * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
2958 * @returns {Observable} An observable sequence of [key, value] pairs from the object.
2959 */
2960 Observable.pairs = function (obj, scheduler) {
2961 scheduler || (scheduler = currentThreadScheduler);
2962 return new PairsObservable(obj, scheduler);
2963 };
2964
2965 var RangeObservable = (function(__super__) {
2966 inherits(RangeObservable, __super__);
2967 function RangeObservable(start, count, scheduler) {
2968 this.start = start;
2969 this.rangeCount = count;
2970 this.scheduler = scheduler;
2971 __super__.call(this);
2972 }
2973
2974 function loopRecursive(start, count, o) {
2975 return function loop (i, recurse) {
2976 if (i < count) {
2977 o.onNext(start + i);
2978 recurse(i + 1);
2979 } else {
2980 o.onCompleted();
2981 }
2982 };
2983 }
2984
2985 RangeObservable.prototype.subscribeCore = function (o) {
2986 return this.scheduler.scheduleRecursive(
2987 0,
2988 loopRecursive(this.start, this.rangeCount, o)
2989 );
2990 };
2991
2992 return RangeObservable;
2993 }(ObservableBase));
2994
2995 /**
2996 * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
2997 * @param {Number} start The value of the first integer in the sequence.
2998 * @param {Number} count The number of sequential integers to generate.
2999 * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
3000 * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
3001 */
3002 Observable.range = function (start, count, scheduler) {
3003 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3004 return new RangeObservable(start, count, scheduler);
3005 };
3006
3007 var RepeatObservable = (function(__super__) {
3008 inherits(RepeatObservable, __super__);
3009 function RepeatObservable(value, repeatCount, scheduler) {
3010 this.value = value;
3011 this.repeatCount = repeatCount == null ? -1 : repeatCount;
3012 this.scheduler = scheduler;
3013 __super__.call(this);
3014 }
3015
3016 RepeatObservable.prototype.subscribeCore = function (observer) {
3017 var sink = new RepeatSink(observer, this);
3018 return sink.run();
3019 };
3020
3021 return RepeatObservable;
3022 }(ObservableBase));
3023
3024 function RepeatSink(observer, parent) {
3025 this.observer = observer;
3026 this.parent = parent;
3027 }
3028
3029 RepeatSink.prototype.run = function () {
3030 var observer = this.observer, value = this.parent.value;
3031 function loopRecursive(i, recurse) {
3032 if (i === -1 || i > 0) {
3033 observer.onNext(value);
3034 i > 0 && i--;
3035 }
3036 if (i === 0) { return observer.onCompleted(); }
3037 recurse(i);
3038 }
3039
3040 return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
3041 };
3042
3043 /**
3044 * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
3045 * @param {Mixed} value Element to repeat.
3046 * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
3047 * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
3048 * @returns {Observable} An observable sequence that repeats the given element the specified number of times.
3049 */
3050 Observable.repeat = function (value, repeatCount, scheduler) {
3051 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3052 return new RepeatObservable(value, repeatCount, scheduler);
3053 };
3054
3055 var JustObservable = (function(__super__) {
3056 inherits(JustObservable, __super__);
3057 function JustObservable(value, scheduler) {
3058 this._value = value;
3059 this._scheduler = scheduler;
3060 __super__.call(this);
3061 }
3062
3063 JustObservable.prototype.subscribeCore = function (o) {
3064 var state = [this._value, o];
3065 return this._scheduler === immediateScheduler ?
3066 scheduleItem(null, state) :
3067 this._scheduler.schedule(state, scheduleItem);
3068 };
3069
3070 function scheduleItem(s, state) {
3071 var value = state[0], observer = state[1];
3072 observer.onNext(value);
3073 observer.onCompleted();
3074 return disposableEmpty;
3075 }
3076
3077 return JustObservable;
3078 }(ObservableBase));
3079
3080 /**
3081 * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
3082 * There is an alias called 'just' or browsers <IE9.
3083 * @param {Mixed} value Single element in the resulting observable sequence.
3084 * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
3085 * @returns {Observable} An observable sequence containing the single specified element.
3086 */
3087 var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
3088 isScheduler(scheduler) || (scheduler = immediateScheduler);
3089 return new JustObservable(value, scheduler);
3090 };
3091
3092 var ThrowObservable = (function(__super__) {
3093 inherits(ThrowObservable, __super__);
3094 function ThrowObservable(error, scheduler) {
3095 this._error = error;
3096 this._scheduler = scheduler;
3097 __super__.call(this);
3098 }
3099
3100 ThrowObservable.prototype.subscribeCore = function (o) {
3101 var state = [this._error, o];
3102 return this._scheduler === immediateScheduler ?
3103 scheduleItem(null, state) :
3104 this._scheduler.schedule(state, scheduleItem);
3105 };
3106
3107 function scheduleItem(s, state) {
3108 var e = state[0], o = state[1];
3109 o.onError(e);
3110 return disposableEmpty;
3111 }
3112
3113 return ThrowObservable;
3114 }(ObservableBase));
3115
3116 /**
3117 * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
3118 * There is an alias to this method called 'throwError' for browsers <IE9.
3119 * @param {Mixed} error An object used for the sequence's termination.
3120 * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
3121 * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
3122 */
3123 var observableThrow = Observable['throw'] = function (error, scheduler) {
3124 isScheduler(scheduler) || (scheduler = immediateScheduler);
3125 return new ThrowObservable(error, scheduler);
3126 };
3127
3128 var UsingObservable = (function (__super__) {
3129 inherits(UsingObservable, __super__);
3130 function UsingObservable(resFn, obsFn) {
3131 this._resFn = resFn;
3132 this._obsFn = obsFn;
3133 __super__.call(this);
3134 }
3135
3136 UsingObservable.prototype.subscribeCore = function (o) {
3137 var disposable = disposableEmpty;
3138 var resource = tryCatch(this._resFn)();
3139 if (resource === errorObj) {
3140 return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
3141 }
3142 resource && (disposable = resource);
3143 var source = tryCatch(this._obsFn)(resource);
3144 if (source === errorObj) {
3145 return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
3146 }
3147 return new BinaryDisposable(source.subscribe(o), disposable);
3148 };
3149
3150 return UsingObservable;
3151 }(ObservableBase));
3152
3153 /**
3154 * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
3155 * @param {Function} resourceFactory Factory function to obtain a resource object.
3156 * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
3157 * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
3158 */
3159 Observable.using = function (resourceFactory, observableFactory) {
3160 return new UsingObservable(resourceFactory, observableFactory);
3161 };
3162
3163 /**
3164 * Propagates the observable sequence or Promise that reacts first.
3165 * @param {Observable} rightSource Second observable sequence or Promise.
3166 * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
3167 */
3168 observableProto.amb = function (rightSource) {
3169 var leftSource = this;
3170 return new AnonymousObservable(function (observer) {
3171 var choice,
3172 leftChoice = 'L', rightChoice = 'R',
3173 leftSubscription = new SingleAssignmentDisposable(),
3174 rightSubscription = new SingleAssignmentDisposable();
3175
3176 isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
3177
3178 function choiceL() {
3179 if (!choice) {
3180 choice = leftChoice;
3181 rightSubscription.dispose();
3182 }
3183 }
3184
3185 function choiceR() {
3186 if (!choice) {
3187 choice = rightChoice;
3188 leftSubscription.dispose();
3189 }
3190 }
3191
3192 var leftSubscribe = observerCreate(
3193 function (left) {
3194 choiceL();
3195 choice === leftChoice && observer.onNext(left);
3196 },
3197 function (e) {
3198 choiceL();
3199 choice === leftChoice && observer.onError(e);
3200 },
3201 function () {
3202 choiceL();
3203 choice === leftChoice && observer.onCompleted();
3204 }
3205 );
3206 var rightSubscribe = observerCreate(
3207 function (right) {
3208 choiceR();
3209 choice === rightChoice && observer.onNext(right);
3210 },
3211 function (e) {
3212 choiceR();
3213 choice === rightChoice && observer.onError(e);
3214 },
3215 function () {
3216 choiceR();
3217 choice === rightChoice && observer.onCompleted();
3218 }
3219 );
3220
3221 leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
3222 rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
3223
3224 return new BinaryDisposable(leftSubscription, rightSubscription);
3225 });
3226 };
3227
3228 function amb(p, c) { return p.amb(c); }
3229
3230 /**
3231 * Propagates the observable sequence or Promise that reacts first.
3232 * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
3233 */
3234 Observable.amb = function () {
3235 var acc = observableNever(), items;
3236 if (Array.isArray(arguments[0])) {
3237 items = arguments[0];
3238 } else {
3239 var len = arguments.length;
3240 items = new Array(items);
3241 for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
3242 }
3243 for (var i = 0, len = items.length; i < len; i++) {
3244 acc = amb(acc, items[i]);
3245 }
3246 return acc;
3247 };
3248
3249 var CatchObservable = (function (__super__) {
3250 inherits(CatchObservable, __super__);
3251 function CatchObservable(source, fn) {
3252 this.source = source;
3253 this._fn = fn;
3254 __super__.call(this);
3255 }
3256
3257 CatchObservable.prototype.subscribeCore = function (o) {
3258 var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
3259 subscription.setDisposable(d1);
3260 d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn)));
3261 return subscription;
3262 };
3263
3264 return CatchObservable;
3265 }(ObservableBase));
3266
3267 var CatchObserver = (function(__super__) {
3268 inherits(CatchObserver, __super__);
3269 function CatchObserver(o, s, fn) {
3270 this._o = o;
3271 this._s = s;
3272 this._fn = fn;
3273 __super__.call(this);
3274 }
3275
3276 CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
3277 CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
3278 CatchObserver.prototype.error = function (e) {
3279 var result = tryCatch(this._fn)(e);
3280 if (result === errorObj) { return this._o.onError(result.e); }
3281 isPromise(result) && (result = observableFromPromise(result));
3282
3283 var d = new SingleAssignmentDisposable();
3284 this._s.setDisposable(d);
3285 d.setDisposable(result.subscribe(this._o));
3286 };
3287
3288 return CatchObserver;
3289 }(AbstractObserver));
3290
3291 /**
3292 * Continues an observable sequence that is terminated by an exception with the next observable sequence.
3293 * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
3294 * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
3295 */
3296 observableProto['catch'] = function (handlerOrSecond) {
3297 return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
3298 };
3299
3300 /**
3301 * Continues an observable sequence that is terminated by an exception with the next observable sequence.
3302 * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
3303 * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
3304 */
3305 var observableCatch = Observable['catch'] = function () {
3306 var items;
3307 if (Array.isArray(arguments[0])) {
3308 items = arguments[0];
3309 } else {
3310 var len = arguments.length;
3311 items = new Array(len);
3312 for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
3313 }
3314 return enumerableOf(items).catchError();
3315 };
3316
3317 /**
3318 * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
3319 * This can be in the form of an argument list of observables or an array.
3320 *
3321 * @example
3322 * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
3323 * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
3324 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
3325 */
3326 observableProto.combineLatest = function () {
3327 var len = arguments.length, args = new Array(len);
3328 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3329 if (Array.isArray(args[0])) {
3330 args[0].unshift(this);
3331 } else {
3332 args.unshift(this);
3333 }
3334 return combineLatest.apply(this, args);
3335 };
3336
3337 function falseFactory() { return false; }
3338 function argumentsToArray() {
3339 var len = arguments.length, args = new Array(len);
3340 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3341 return args;
3342 }
3343
3344 var CombineLatestObservable = (function(__super__) {
3345 inherits(CombineLatestObservable, __super__);
3346 function CombineLatestObservable(params, cb) {
3347 this._params = params;
3348 this._cb = cb;
3349 __super__.call(this);
3350 }
3351
3352 CombineLatestObservable.prototype.subscribeCore = function(observer) {
3353 var len = this._params.length,
3354 subscriptions = new Array(len);
3355
3356 var state = {
3357 hasValue: arrayInitialize(len, falseFactory),
3358 hasValueAll: false,
3359 isDone: arrayInitialize(len, falseFactory),
3360 values: new Array(len)
3361 };
3362
3363 for (var i = 0; i < len; i++) {
3364 var source = this._params[i], sad = new SingleAssignmentDisposable();
3365 subscriptions[i] = sad;
3366 isPromise(source) && (source = observableFromPromise(source));
3367 sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
3368 }
3369
3370 return new NAryDisposable(subscriptions);
3371 };
3372
3373 return CombineLatestObservable;
3374 }(ObservableBase));
3375
3376 var CombineLatestObserver = (function (__super__) {
3377 inherits(CombineLatestObserver, __super__);
3378 function CombineLatestObserver(o, i, cb, state) {
3379 this._o = o;
3380 this._i = i;
3381 this._cb = cb;
3382 this._state = state;
3383 __super__.call(this);
3384 }
3385
3386 function notTheSame(i) {
3387 return function (x, j) {
3388 return j !== i;
3389 };
3390 }
3391
3392 CombineLatestObserver.prototype.next = function (x) {
3393 this._state.values[this._i] = x;
3394 this._state.hasValue[this._i] = true;
3395 if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
3396 var res = tryCatch(this._cb).apply(null, this._state.values);
3397 if (res === errorObj) { return this._o.onError(res.e); }
3398 this._o.onNext(res);
3399 } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
3400 this._o.onCompleted();
3401 }
3402 };
3403
3404 CombineLatestObserver.prototype.error = function (e) {
3405 this._o.onError(e);
3406 };
3407
3408 CombineLatestObserver.prototype.completed = function () {
3409 this._state.isDone[this._i] = true;
3410 this._state.isDone.every(identity) && this._o.onCompleted();
3411 };
3412
3413 return CombineLatestObserver;
3414 }(AbstractObserver));
3415
3416 /**
3417 * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
3418 *
3419 * @example
3420 * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
3421 * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
3422 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
3423 */
3424 var combineLatest = Observable.combineLatest = function () {
3425 var len = arguments.length, args = new Array(len);
3426 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3427 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
3428 Array.isArray(args[0]) && (args = args[0]);
3429 return new CombineLatestObservable(args, resultSelector);
3430 };
3431
3432 /**
3433 * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
3434 * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
3435 */
3436 observableProto.concat = function () {
3437 for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
3438 args.unshift(this);
3439 return observableConcat.apply(null, args);
3440 };
3441
3442 var ConcatObserver = (function(__super__) {
3443 inherits(ConcatObserver, __super__);
3444 function ConcatObserver(s, fn) {
3445 this._s = s;
3446 this._fn = fn;
3447 __super__.call(this);
3448 }
3449
3450 ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); };
3451 ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); };
3452 ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); };
3453
3454 return ConcatObserver;
3455 }(AbstractObserver));
3456
3457 var ConcatObservable = (function(__super__) {
3458 inherits(ConcatObservable, __super__);
3459 function ConcatObservable(sources) {
3460 this._sources = sources;
3461 __super__.call(this);
3462 }
3463
3464 function scheduleRecursive (state, recurse) {
3465 if (state.disposable.isDisposed) { return; }
3466 if (state.i === state.sources.length) { return state.o.onCompleted(); }
3467
3468 // Check if promise
3469 var currentValue = state.sources[state.i];
3470 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
3471
3472 var d = new SingleAssignmentDisposable();
3473 state.subscription.setDisposable(d);
3474 d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse)));
3475 }
3476
3477 ConcatObservable.prototype.subscribeCore = function(o) {
3478 var subscription = new SerialDisposable();
3479 var disposable = disposableCreate(noop);
3480 var state = {
3481 o: o,
3482 i: 0,
3483 subscription: subscription,
3484 disposable: disposable,
3485 sources: this._sources
3486 };
3487
3488 var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive);
3489 return new NAryDisposable([subscription, disposable, cancelable]);
3490 };
3491
3492 return ConcatObservable;
3493 }(ObservableBase));
3494
3495 /**
3496 * Concatenates all the observable sequences.
3497 * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
3498 * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
3499 */
3500 var observableConcat = Observable.concat = function () {
3501 var args;
3502 if (Array.isArray(arguments[0])) {
3503 args = arguments[0];
3504 } else {
3505 args = new Array(arguments.length);
3506 for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
3507 }
3508 return new ConcatObservable(args);
3509 };
3510
3511 /**
3512 * Concatenates an observable sequence of observable sequences.
3513 * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
3514 */
3515 observableProto.concatAll = function () {
3516 return this.merge(1);
3517 };
3518
3519 var MergeObservable = (function (__super__) {
3520 inherits(MergeObservable, __super__);
3521
3522 function MergeObservable(source, maxConcurrent) {
3523 this.source = source;
3524 this.maxConcurrent = maxConcurrent;
3525 __super__.call(this);
3526 }
3527
3528 MergeObservable.prototype.subscribeCore = function(observer) {
3529 var g = new CompositeDisposable();
3530 g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
3531 return g;
3532 };
3533
3534 return MergeObservable;
3535
3536 }(ObservableBase));
3537
3538 var MergeObserver = (function (__super__) {
3539 function MergeObserver(o, max, g) {
3540 this.o = o;
3541 this.max = max;
3542 this.g = g;
3543 this.done = false;
3544 this.q = [];
3545 this.activeCount = 0;
3546 __super__.call(this);
3547 }
3548
3549 inherits(MergeObserver, __super__);
3550
3551 MergeObserver.prototype.handleSubscribe = function (xs) {
3552 var sad = new SingleAssignmentDisposable();
3553 this.g.add(sad);
3554 isPromise(xs) && (xs = observableFromPromise(xs));
3555 sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
3556 };
3557
3558 MergeObserver.prototype.next = function (innerSource) {
3559 if(this.activeCount < this.max) {
3560 this.activeCount++;
3561 this.handleSubscribe(innerSource);
3562 } else {
3563 this.q.push(innerSource);
3564 }
3565 };
3566 MergeObserver.prototype.error = function (e) { this.o.onError(e); };
3567 MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); };
3568
3569 function InnerObserver(parent, sad) {
3570 this.parent = parent;
3571 this.sad = sad;
3572 __super__.call(this);
3573 }
3574
3575 inherits(InnerObserver, __super__);
3576
3577 InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); };
3578 InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); };
3579 InnerObserver.prototype.completed = function () {
3580 this.parent.g.remove(this.sad);
3581 if (this.parent.q.length > 0) {
3582 this.parent.handleSubscribe(this.parent.q.shift());
3583 } else {
3584 this.parent.activeCount--;
3585 this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();
3586 }
3587 };
3588
3589 return MergeObserver;
3590 }(AbstractObserver));
3591
3592 /**
3593 * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
3594 * Or merges two observable sequences into a single observable sequence.
3595 * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
3596 * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
3597 */
3598 observableProto.merge = function (maxConcurrentOrOther) {
3599 return typeof maxConcurrentOrOther !== 'number' ?
3600 observableMerge(this, maxConcurrentOrOther) :
3601 new MergeObservable(this, maxConcurrentOrOther);
3602 };
3603
3604 /**
3605 * Merges all the observable sequences into a single observable sequence.
3606 * The scheduler is optional and if not specified, the immediate scheduler is used.
3607 * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
3608 */
3609 var observableMerge = Observable.merge = function () {
3610 var scheduler, sources = [], i, len = arguments.length;
3611 if (!arguments[0]) {
3612 scheduler = immediateScheduler;
3613 for(i = 1; i < len; i++) { sources.push(arguments[i]); }
3614 } else if (isScheduler(arguments[0])) {
3615 scheduler = arguments[0];
3616 for(i = 1; i < len; i++) { sources.push(arguments[i]); }
3617 } else {
3618 scheduler = immediateScheduler;
3619 for(i = 0; i < len; i++) { sources.push(arguments[i]); }
3620 }
3621 if (Array.isArray(sources[0])) {
3622 sources = sources[0];
3623 }
3624 return observableOf(scheduler, sources).mergeAll();
3625 };
3626
3627 var CompositeError = Rx.CompositeError = function(errors) {
3628 this.innerErrors = errors;
3629 this.message = 'This contains multiple errors. Check the innerErrors';
3630 Error.call(this);
3631 };
3632 CompositeError.prototype = Object.create(Error.prototype);
3633 CompositeError.prototype.name = 'CompositeError';
3634
3635 var MergeDelayErrorObservable = (function(__super__) {
3636 inherits(MergeDelayErrorObservable, __super__);
3637 function MergeDelayErrorObservable(source) {
3638 this.source = source;
3639 __super__.call(this);
3640 }
3641
3642 MergeDelayErrorObservable.prototype.subscribeCore = function (o) {
3643 var group = new CompositeDisposable(),
3644 m = new SingleAssignmentDisposable(),
3645 state = { isStopped: false, errors: [], o: o };
3646
3647 group.add(m);
3648 m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));
3649
3650 return group;
3651 };
3652
3653 return MergeDelayErrorObservable;
3654 }(ObservableBase));
3655
3656 var MergeDelayErrorObserver = (function(__super__) {
3657 inherits(MergeDelayErrorObserver, __super__);
3658 function MergeDelayErrorObserver(group, state) {
3659 this._group = group;
3660 this._state = state;
3661 __super__.call(this);
3662 }
3663
3664 function setCompletion(o, errors) {
3665 if (errors.length === 0) {
3666 o.onCompleted();
3667 } else if (errors.length === 1) {
3668 o.onError(errors[0]);
3669 } else {
3670 o.onError(new CompositeError(errors));
3671 }
3672 }
3673
3674 MergeDelayErrorObserver.prototype.next = function (x) {
3675 var inner = new SingleAssignmentDisposable();
3676 this._group.add(inner);
3677
3678 // Check for promises support
3679 isPromise(x) && (x = observableFromPromise(x));
3680 inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));
3681 };
3682
3683 MergeDelayErrorObserver.prototype.error = function (e) {
3684 this._state.errors.push(e);
3685 this._state.isStopped = true;
3686 this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
3687 };
3688
3689 MergeDelayErrorObserver.prototype.completed = function () {
3690 this._state.isStopped = true;
3691 this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
3692 };
3693
3694 inherits(InnerObserver, __super__);
3695 function InnerObserver(inner, group, state) {
3696 this._inner = inner;
3697 this._group = group;
3698 this._state = state;
3699 __super__.call(this);
3700 }
3701
3702 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
3703 InnerObserver.prototype.error = function (e) {
3704 this._state.errors.push(e);
3705 this._group.remove(this._inner);
3706 this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
3707 };
3708 InnerObserver.prototype.completed = function () {
3709 this._group.remove(this._inner);
3710 this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
3711 };
3712
3713 return MergeDelayErrorObserver;
3714 }(AbstractObserver));
3715
3716 /**
3717 * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
3718 * receive all successfully emitted items from all of the source Observables without being interrupted by
3719 * an error notification from one of them.
3720 *
3721 * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
3722 * error via the Observer's onError, mergeDelayError will refrain from propagating that
3723 * error notification until all of the merged Observables have finished emitting items.
3724 * @param {Array | Arguments} args Arguments or an array to merge.
3725 * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
3726 */
3727 Observable.mergeDelayError = function() {
3728 var args;
3729 if (Array.isArray(arguments[0])) {
3730 args = arguments[0];
3731 } else {
3732 var len = arguments.length;
3733 args = new Array(len);
3734 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3735 }
3736 var source = observableOf(null, args);
3737 return new MergeDelayErrorObservable(source);
3738 };
3739
3740 var MergeAllObservable = (function (__super__) {
3741 inherits(MergeAllObservable, __super__);
3742
3743 function MergeAllObservable(source) {
3744 this.source = source;
3745 __super__.call(this);
3746 }
3747
3748 MergeAllObservable.prototype.subscribeCore = function (o) {
3749 var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
3750 g.add(m);
3751 m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));
3752 return g;
3753 };
3754
3755 return MergeAllObservable;
3756 }(ObservableBase));
3757
3758 var MergeAllObserver = (function (__super__) {
3759 function MergeAllObserver(o, g) {
3760 this.o = o;
3761 this.g = g;
3762 this.done = false;
3763 __super__.call(this);
3764 }
3765
3766 inherits(MergeAllObserver, __super__);
3767
3768 MergeAllObserver.prototype.next = function(innerSource) {
3769 var sad = new SingleAssignmentDisposable();
3770 this.g.add(sad);
3771 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
3772 sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
3773 };
3774
3775 MergeAllObserver.prototype.error = function (e) {
3776 this.o.onError(e);
3777 };
3778
3779 MergeAllObserver.prototype.completed = function () {
3780 this.done = true;
3781 this.g.length === 1 && this.o.onCompleted();
3782 };
3783
3784 function InnerObserver(parent, sad) {
3785 this.parent = parent;
3786 this.sad = sad;
3787 __super__.call(this);
3788 }
3789
3790 inherits(InnerObserver, __super__);
3791
3792 InnerObserver.prototype.next = function (x) {
3793 this.parent.o.onNext(x);
3794 };
3795 InnerObserver.prototype.error = function (e) {
3796 this.parent.o.onError(e);
3797 };
3798 InnerObserver.prototype.completed = function () {
3799 this.parent.g.remove(this.sad);
3800 this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();
3801 };
3802
3803 return MergeAllObserver;
3804 }(AbstractObserver));
3805
3806 /**
3807 * Merges an observable sequence of observable sequences into an observable sequence.
3808 * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
3809 */
3810 observableProto.mergeAll = function () {
3811 return new MergeAllObservable(this);
3812 };
3813
3814 /**
3815 * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
3816 * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
3817 * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
3818 */
3819 observableProto.onErrorResumeNext = function (second) {
3820 if (!second) { throw new Error('Second observable is required'); }
3821 return onErrorResumeNext([this, second]);
3822 };
3823
3824 var OnErrorResumeNextObservable = (function(__super__) {
3825 inherits(OnErrorResumeNextObservable, __super__);
3826 function OnErrorResumeNextObservable(sources) {
3827 this.sources = sources;
3828 __super__.call(this);
3829 }
3830
3831 function scheduleMethod(state, recurse) {
3832 if (state.pos < state.sources.length) {
3833 var current = state.sources[state.pos++];
3834 isPromise(current) && (current = observableFromPromise(current));
3835 var d = new SingleAssignmentDisposable();
3836 state.subscription.setDisposable(d);
3837 d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));
3838 } else {
3839 state.o.onCompleted();
3840 }
3841 }
3842
3843 OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {
3844 var subscription = new SerialDisposable(),
3845 state = {pos: 0, subscription: subscription, o: o, sources: this.sources },
3846 cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);
3847
3848 return new BinaryDisposable(subscription, cancellable);
3849 };
3850
3851 return OnErrorResumeNextObservable;
3852 }(ObservableBase));
3853
3854 var OnErrorResumeNextObserver = (function(__super__) {
3855 inherits(OnErrorResumeNextObserver, __super__);
3856 function OnErrorResumeNextObserver(state, recurse) {
3857 this._state = state;
3858 this._recurse = recurse;
3859 __super__.call(this);
3860 }
3861
3862 OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };
3863 OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };
3864 OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };
3865
3866 return OnErrorResumeNextObserver;
3867 }(AbstractObserver));
3868
3869 /**
3870 * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
3871 * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
3872 */
3873 var onErrorResumeNext = Observable.onErrorResumeNext = function () {
3874 var sources = [];
3875 if (Array.isArray(arguments[0])) {
3876 sources = arguments[0];
3877 } else {
3878 var len = arguments.length;
3879 sources = new Array(len);
3880 for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
3881 }
3882 return new OnErrorResumeNextObservable(sources);
3883 };
3884
3885 var SkipUntilObservable = (function(__super__) {
3886 inherits(SkipUntilObservable, __super__);
3887
3888 function SkipUntilObservable(source, other) {
3889 this._s = source;
3890 this._o = isPromise(other) ? observableFromPromise(other) : other;
3891 this._open = false;
3892 __super__.call(this);
3893 }
3894
3895 SkipUntilObservable.prototype.subscribeCore = function(o) {
3896 var leftSubscription = new SingleAssignmentDisposable();
3897 leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));
3898
3899 isPromise(this._o) && (this._o = observableFromPromise(this._o));
3900
3901 var rightSubscription = new SingleAssignmentDisposable();
3902 rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));
3903
3904 return new BinaryDisposable(leftSubscription, rightSubscription);
3905 };
3906
3907 return SkipUntilObservable;
3908 }(ObservableBase));
3909
3910 var SkipUntilSourceObserver = (function(__super__) {
3911 inherits(SkipUntilSourceObserver, __super__);
3912 function SkipUntilSourceObserver(o, p) {
3913 this._o = o;
3914 this._p = p;
3915 __super__.call(this);
3916 }
3917
3918 SkipUntilSourceObserver.prototype.next = function (x) {
3919 this._p._open && this._o.onNext(x);
3920 };
3921
3922 SkipUntilSourceObserver.prototype.error = function (err) {
3923 this._o.onError(err);
3924 };
3925
3926 SkipUntilSourceObserver.prototype.onCompleted = function () {
3927 this._p._open && this._o.onCompleted();
3928 };
3929
3930 return SkipUntilSourceObserver;
3931 }(AbstractObserver));
3932
3933 var SkipUntilOtherObserver = (function(__super__) {
3934 inherits(SkipUntilOtherObserver, __super__);
3935 function SkipUntilOtherObserver(o, p, r) {
3936 this._o = o;
3937 this._p = p;
3938 this._r = r;
3939 __super__.call(this);
3940 }
3941
3942 SkipUntilOtherObserver.prototype.next = function () {
3943 this._p._open = true;
3944 this._r.dispose();
3945 };
3946
3947 SkipUntilOtherObserver.prototype.error = function (err) {
3948 this._o.onError(err);
3949 };
3950
3951 SkipUntilOtherObserver.prototype.onCompleted = function () {
3952 this._r.dispose();
3953 };
3954
3955 return SkipUntilOtherObserver;
3956 }(AbstractObserver));
3957
3958 /**
3959 * Returns the values from the source observable sequence only after the other observable sequence produces a value.
3960 * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
3961 * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
3962 */
3963 observableProto.skipUntil = function (other) {
3964 return new SkipUntilObservable(this, other);
3965 };
3966
3967 var SwitchObservable = (function(__super__) {
3968 inherits(SwitchObservable, __super__);
3969 function SwitchObservable(source) {
3970 this.source = source;
3971 __super__.call(this);
3972 }
3973
3974 SwitchObservable.prototype.subscribeCore = function (o) {
3975 var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
3976 return new BinaryDisposable(s, inner);
3977 };
3978
3979 inherits(SwitchObserver, AbstractObserver);
3980 function SwitchObserver(o, inner) {
3981 this.o = o;
3982 this.inner = inner;
3983 this.stopped = false;
3984 this.latest = 0;
3985 this.hasLatest = false;
3986 AbstractObserver.call(this);
3987 }
3988
3989 SwitchObserver.prototype.next = function (innerSource) {
3990 var d = new SingleAssignmentDisposable(), id = ++this.latest;
3991 this.hasLatest = true;
3992 this.inner.setDisposable(d);
3993 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
3994 d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
3995 };
3996
3997 SwitchObserver.prototype.error = function (e) {
3998 this.o.onError(e);
3999 };
4000
4001 SwitchObserver.prototype.completed = function () {
4002 this.stopped = true;
4003 !this.hasLatest && this.o.onCompleted();
4004 };
4005
4006 inherits(InnerObserver, AbstractObserver);
4007 function InnerObserver(parent, id) {
4008 this.parent = parent;
4009 this.id = id;
4010 AbstractObserver.call(this);
4011 }
4012 InnerObserver.prototype.next = function (x) {
4013 this.parent.latest === this.id && this.parent.o.onNext(x);
4014 };
4015
4016 InnerObserver.prototype.error = function (e) {
4017 this.parent.latest === this.id && this.parent.o.onError(e);
4018 };
4019
4020 InnerObserver.prototype.completed = function () {
4021 if (this.parent.latest === this.id) {
4022 this.parent.hasLatest = false;
4023 this.parent.stopped && this.parent.o.onCompleted();
4024 }
4025 };
4026
4027 return SwitchObservable;
4028 }(ObservableBase));
4029
4030 /**
4031 * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
4032 * @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.
4033 */
4034 observableProto['switch'] = observableProto.switchLatest = function () {
4035 return new SwitchObservable(this);
4036 };
4037
4038 var TakeUntilObservable = (function(__super__) {
4039 inherits(TakeUntilObservable, __super__);
4040
4041 function TakeUntilObservable(source, other) {
4042 this.source = source;
4043 this.other = isPromise(other) ? observableFromPromise(other) : other;
4044 __super__.call(this);
4045 }
4046
4047 TakeUntilObservable.prototype.subscribeCore = function(o) {
4048 return new BinaryDisposable(
4049 this.source.subscribe(o),
4050 this.other.subscribe(new TakeUntilObserver(o))
4051 );
4052 };
4053
4054 return TakeUntilObservable;
4055 }(ObservableBase));
4056
4057 var TakeUntilObserver = (function(__super__) {
4058 inherits(TakeUntilObserver, __super__);
4059 function TakeUntilObserver(o) {
4060 this._o = o;
4061 __super__.call(this);
4062 }
4063
4064 TakeUntilObserver.prototype.next = function () {
4065 this._o.onCompleted();
4066 };
4067
4068 TakeUntilObserver.prototype.error = function (err) {
4069 this._o.onError(err);
4070 };
4071
4072 TakeUntilObserver.prototype.onCompleted = noop;
4073
4074 return TakeUntilObserver;
4075 }(AbstractObserver));
4076
4077 /**
4078 * Returns the values from the source observable sequence until the other observable sequence produces a value.
4079 * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
4080 * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
4081 */
4082 observableProto.takeUntil = function (other) {
4083 return new TakeUntilObservable(this, other);
4084 };
4085
4086 function falseFactory() { return false; }
4087 function argumentsToArray() {
4088 var len = arguments.length, args = new Array(len);
4089 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4090 return args;
4091 }
4092
4093 var WithLatestFromObservable = (function(__super__) {
4094 inherits(WithLatestFromObservable, __super__);
4095 function WithLatestFromObservable(source, sources, resultSelector) {
4096 this._s = source;
4097 this._ss = sources;
4098 this._cb = resultSelector;
4099 __super__.call(this);
4100 }
4101
4102 WithLatestFromObservable.prototype.subscribeCore = function (o) {
4103 var len = this._ss.length;
4104 var state = {
4105 hasValue: arrayInitialize(len, falseFactory),
4106 hasValueAll: false,
4107 values: new Array(len)
4108 };
4109
4110 var n = this._ss.length, subscriptions = new Array(n + 1);
4111 for (var i = 0; i < n; i++) {
4112 var other = this._ss[i], sad = new SingleAssignmentDisposable();
4113 isPromise(other) && (other = observableFromPromise(other));
4114 sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));
4115 subscriptions[i] = sad;
4116 }
4117
4118 var outerSad = new SingleAssignmentDisposable();
4119 outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));
4120 subscriptions[n] = outerSad;
4121
4122 return new NAryDisposable(subscriptions);
4123 };
4124
4125 return WithLatestFromObservable;
4126 }(ObservableBase));
4127
4128 var WithLatestFromOtherObserver = (function (__super__) {
4129 inherits(WithLatestFromOtherObserver, __super__);
4130 function WithLatestFromOtherObserver(o, i, state) {
4131 this._o = o;
4132 this._i = i;
4133 this._state = state;
4134 __super__.call(this);
4135 }
4136
4137 WithLatestFromOtherObserver.prototype.next = function (x) {
4138 this._state.values[this._i] = x;
4139 this._state.hasValue[this._i] = true;
4140 this._state.hasValueAll = this._state.hasValue.every(identity);
4141 };
4142
4143 WithLatestFromOtherObserver.prototype.error = function (e) {
4144 this._o.onError(e);
4145 };
4146
4147 WithLatestFromOtherObserver.prototype.completed = noop;
4148
4149 return WithLatestFromOtherObserver;
4150 }(AbstractObserver));
4151
4152 var WithLatestFromSourceObserver = (function (__super__) {
4153 inherits(WithLatestFromSourceObserver, __super__);
4154 function WithLatestFromSourceObserver(o, cb, state) {
4155 this._o = o;
4156 this._cb = cb;
4157 this._state = state;
4158 __super__.call(this);
4159 }
4160
4161 WithLatestFromSourceObserver.prototype.next = function (x) {
4162 var allValues = [x].concat(this._state.values);
4163 if (!this._state.hasValueAll) { return; }
4164 var res = tryCatch(this._cb).apply(null, allValues);
4165 if (res === errorObj) { return this._o.onError(res.e); }
4166 this._o.onNext(res);
4167 };
4168
4169 WithLatestFromSourceObserver.prototype.error = function (e) {
4170 this._o.onError(e);
4171 };
4172
4173 WithLatestFromSourceObserver.prototype.completed = function () {
4174 this._o.onCompleted();
4175 };
4176
4177 return WithLatestFromSourceObserver;
4178 }(AbstractObserver));
4179
4180 /**
4181 * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
4182 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
4183 */
4184 observableProto.withLatestFrom = function () {
4185 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4186
4187 var len = arguments.length, args = new Array(len);
4188 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4189 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4190 Array.isArray(args[0]) && (args = args[0]);
4191
4192 return new WithLatestFromObservable(this, args, resultSelector);
4193 };
4194
4195 function falseFactory() { return false; }
4196 function emptyArrayFactory() { return []; }
4197
4198 var ZipObservable = (function(__super__) {
4199 inherits(ZipObservable, __super__);
4200 function ZipObservable(sources, resultSelector) {
4201 this._s = sources;
4202 this._cb = resultSelector;
4203 __super__.call(this);
4204 }
4205
4206 ZipObservable.prototype.subscribeCore = function(observer) {
4207 var n = this._s.length,
4208 subscriptions = new Array(n),
4209 done = arrayInitialize(n, falseFactory),
4210 q = arrayInitialize(n, emptyArrayFactory);
4211
4212 for (var i = 0; i < n; i++) {
4213 var source = this._s[i], sad = new SingleAssignmentDisposable();
4214 subscriptions[i] = sad;
4215 isPromise(source) && (source = observableFromPromise(source));
4216 sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));
4217 }
4218
4219 return new NAryDisposable(subscriptions);
4220 };
4221
4222 return ZipObservable;
4223 }(ObservableBase));
4224
4225 var ZipObserver = (function (__super__) {
4226 inherits(ZipObserver, __super__);
4227 function ZipObserver(o, i, p, q, d) {
4228 this._o = o;
4229 this._i = i;
4230 this._p = p;
4231 this._q = q;
4232 this._d = d;
4233 __super__.call(this);
4234 }
4235
4236 function notEmpty(x) { return x.length > 0; }
4237 function shiftEach(x) { return x.shift(); }
4238 function notTheSame(i) {
4239 return function (x, j) {
4240 return j !== i;
4241 };
4242 }
4243
4244 ZipObserver.prototype.next = function (x) {
4245 this._q[this._i].push(x);
4246 if (this._q.every(notEmpty)) {
4247 var queuedValues = this._q.map(shiftEach);
4248 var res = tryCatch(this._p._cb).apply(null, queuedValues);
4249 if (res === errorObj) { return this._o.onError(res.e); }
4250 this._o.onNext(res);
4251 } else if (this._d.filter(notTheSame(this._i)).every(identity)) {
4252 this._o.onCompleted();
4253 }
4254 };
4255
4256 ZipObserver.prototype.error = function (e) {
4257 this._o.onError(e);
4258 };
4259
4260 ZipObserver.prototype.completed = function () {
4261 this._d[this._i] = true;
4262 this._d.every(identity) && this._o.onCompleted();
4263 };
4264
4265 return ZipObserver;
4266 }(AbstractObserver));
4267
4268 /**
4269 * 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.
4270 * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
4271 * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
4272 */
4273 observableProto.zip = function () {
4274 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4275
4276 var len = arguments.length, args = new Array(len);
4277 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4278 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4279 Array.isArray(args[0]) && (args = args[0]);
4280
4281 var parent = this;
4282 args.unshift(parent);
4283
4284 return new ZipObservable(args, resultSelector);
4285 };
4286
4287 /**
4288 * 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.
4289 * @param arguments Observable sources.
4290 * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
4291 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
4292 */
4293 Observable.zip = function () {
4294 var len = arguments.length, args = new Array(len);
4295 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4296 if (Array.isArray(args[0])) {
4297 args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
4298 }
4299 var first = args.shift();
4300 return first.zip.apply(first, args);
4301 };
4302
4303function falseFactory() { return false; }
4304function emptyArrayFactory() { return []; }
4305function argumentsToArray() {
4306 var len = arguments.length, args = new Array(len);
4307 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4308 return args;
4309}
4310
4311var ZipIterableObservable = (function(__super__) {
4312 inherits(ZipIterableObservable, __super__);
4313 function ZipIterableObservable(sources, cb) {
4314 this.sources = sources;
4315 this._cb = cb;
4316 __super__.call(this);
4317 }
4318
4319 ZipIterableObservable.prototype.subscribeCore = function (o) {
4320 var sources = this.sources, len = sources.length, subscriptions = new Array(len);
4321
4322 var state = {
4323 q: arrayInitialize(len, emptyArrayFactory),
4324 done: arrayInitialize(len, falseFactory),
4325 cb: this._cb,
4326 o: o
4327 };
4328
4329 for (var i = 0; i < len; i++) {
4330 (function (i) {
4331 var source = sources[i], sad = new SingleAssignmentDisposable();
4332 (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
4333
4334 subscriptions[i] = sad;
4335 sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));
4336 }(i));
4337 }
4338
4339 return new NAryDisposable(subscriptions);
4340 };
4341
4342 return ZipIterableObservable;
4343}(ObservableBase));
4344
4345var ZipIterableObserver = (function (__super__) {
4346 inherits(ZipIterableObserver, __super__);
4347 function ZipIterableObserver(s, i) {
4348 this._s = s;
4349 this._i = i;
4350 __super__.call(this);
4351 }
4352
4353 function notEmpty(x) { return x.length > 0; }
4354 function shiftEach(x) { return x.shift(); }
4355 function notTheSame(i) {
4356 return function (x, j) {
4357 return j !== i;
4358 };
4359 }
4360
4361 ZipIterableObserver.prototype.next = function (x) {
4362 this._s.q[this._i].push(x);
4363 if (this._s.q.every(notEmpty)) {
4364 var queuedValues = this._s.q.map(shiftEach),
4365 res = tryCatch(this._s.cb).apply(null, queuedValues);
4366 if (res === errorObj) { return this._s.o.onError(res.e); }
4367 this._s.o.onNext(res);
4368 } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {
4369 this._s.o.onCompleted();
4370 }
4371 };
4372
4373 ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };
4374
4375 ZipIterableObserver.prototype.completed = function () {
4376 this._s.done[this._i] = true;
4377 this._s.done.every(identity) && this._s.o.onCompleted();
4378 };
4379
4380 return ZipIterableObserver;
4381}(AbstractObserver));
4382
4383/**
4384 * 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.
4385 * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
4386 * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
4387 */
4388observableProto.zipIterable = function () {
4389 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4390
4391 var len = arguments.length, args = new Array(len);
4392 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4393 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4394
4395 var parent = this;
4396 args.unshift(parent);
4397 return new ZipIterableObservable(args, resultSelector);
4398};
4399
4400 function asObservable(source) {
4401 return function subscribe(o) { return source.subscribe(o); };
4402 }
4403
4404 /**
4405 * Hides the identity of an observable sequence.
4406 * @returns {Observable} An observable sequence that hides the identity of the source sequence.
4407 */
4408 observableProto.asObservable = function () {
4409 return new AnonymousObservable(asObservable(this), this);
4410 };
4411
4412 function toArray(x) { return x.toArray(); }
4413 function notEmpty(x) { return x.length > 0; }
4414
4415 /**
4416 * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
4417 * @param {Number} count Length of each buffer.
4418 * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
4419 * @returns {Observable} An observable sequence of buffers.
4420 */
4421 observableProto.bufferWithCount = function (count, skip) {
4422 typeof skip !== 'number' && (skip = count);
4423 return this.windowWithCount(count, skip)
4424 .flatMap(toArray)
4425 .filter(notEmpty);
4426 };
4427
4428 var DematerializeObservable = (function (__super__) {
4429 inherits(DematerializeObservable, __super__);
4430 function DematerializeObservable(source) {
4431 this.source = source;
4432 __super__.call(this);
4433 }
4434
4435 DematerializeObservable.prototype.subscribeCore = function (o) {
4436 return this.source.subscribe(new DematerializeObserver(o));
4437 };
4438
4439 return DematerializeObservable;
4440 }(ObservableBase));
4441
4442 var DematerializeObserver = (function (__super__) {
4443 inherits(DematerializeObserver, __super__);
4444
4445 function DematerializeObserver(o) {
4446 this._o = o;
4447 __super__.call(this);
4448 }
4449
4450 DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };
4451 DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };
4452 DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };
4453
4454 return DematerializeObserver;
4455 }(AbstractObserver));
4456
4457 /**
4458 * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
4459 * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
4460 */
4461 observableProto.dematerialize = function () {
4462 return new DematerializeObservable(this);
4463 };
4464
4465 var DistinctUntilChangedObservable = (function(__super__) {
4466 inherits(DistinctUntilChangedObservable, __super__);
4467 function DistinctUntilChangedObservable(source, keyFn, comparer) {
4468 this.source = source;
4469 this.keyFn = keyFn;
4470 this.comparer = comparer;
4471 __super__.call(this);
4472 }
4473
4474 DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
4475 return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
4476 };
4477
4478 return DistinctUntilChangedObservable;
4479 }(ObservableBase));
4480
4481 var DistinctUntilChangedObserver = (function(__super__) {
4482 inherits(DistinctUntilChangedObserver, __super__);
4483 function DistinctUntilChangedObserver(o, keyFn, comparer) {
4484 this.o = o;
4485 this.keyFn = keyFn;
4486 this.comparer = comparer;
4487 this.hasCurrentKey = false;
4488 this.currentKey = null;
4489 __super__.call(this);
4490 }
4491
4492 DistinctUntilChangedObserver.prototype.next = function (x) {
4493 var key = x, comparerEquals;
4494 if (isFunction(this.keyFn)) {
4495 key = tryCatch(this.keyFn)(x);
4496 if (key === errorObj) { return this.o.onError(key.e); }
4497 }
4498 if (this.hasCurrentKey) {
4499 comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
4500 if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
4501 }
4502 if (!this.hasCurrentKey || !comparerEquals) {
4503 this.hasCurrentKey = true;
4504 this.currentKey = key;
4505 this.o.onNext(x);
4506 }
4507 };
4508 DistinctUntilChangedObserver.prototype.error = function(e) {
4509 this.o.onError(e);
4510 };
4511 DistinctUntilChangedObserver.prototype.completed = function () {
4512 this.o.onCompleted();
4513 };
4514
4515 return DistinctUntilChangedObserver;
4516 }(AbstractObserver));
4517
4518 /**
4519 * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
4520 * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
4521 * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
4522 * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
4523 */
4524 observableProto.distinctUntilChanged = function (keyFn, comparer) {
4525 comparer || (comparer = defaultComparer);
4526 return new DistinctUntilChangedObservable(this, keyFn, comparer);
4527 };
4528
4529 var TapObservable = (function(__super__) {
4530 inherits(TapObservable,__super__);
4531 function TapObservable(source, observerOrOnNext, onError, onCompleted) {
4532 this.source = source;
4533 this._oN = observerOrOnNext;
4534 this._oE = onError;
4535 this._oC = onCompleted;
4536 __super__.call(this);
4537 }
4538
4539 TapObservable.prototype.subscribeCore = function(o) {
4540 return this.source.subscribe(new InnerObserver(o, this));
4541 };
4542
4543 inherits(InnerObserver, AbstractObserver);
4544 function InnerObserver(o, p) {
4545 this.o = o;
4546 this.t = !p._oN || isFunction(p._oN) ?
4547 observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
4548 p._oN;
4549 this.isStopped = false;
4550 AbstractObserver.call(this);
4551 }
4552 InnerObserver.prototype.next = function(x) {
4553 var res = tryCatch(this.t.onNext).call(this.t, x);
4554 if (res === errorObj) { this.o.onError(res.e); }
4555 this.o.onNext(x);
4556 };
4557 InnerObserver.prototype.error = function(err) {
4558 var res = tryCatch(this.t.onError).call(this.t, err);
4559 if (res === errorObj) { return this.o.onError(res.e); }
4560 this.o.onError(err);
4561 };
4562 InnerObserver.prototype.completed = function() {
4563 var res = tryCatch(this.t.onCompleted).call(this.t);
4564 if (res === errorObj) { return this.o.onError(res.e); }
4565 this.o.onCompleted();
4566 };
4567
4568 return TapObservable;
4569 }(ObservableBase));
4570
4571 /**
4572 * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
4573 * 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.
4574 * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
4575 * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
4576 * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
4577 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4578 */
4579 observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
4580 return new TapObservable(this, observerOrOnNext, onError, onCompleted);
4581 };
4582
4583 /**
4584 * Invokes an action for each element in the observable sequence.
4585 * 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.
4586 * @param {Function} onNext Action to invoke for each element in the observable sequence.
4587 * @param {Any} [thisArg] Object to use as this when executing callback.
4588 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4589 */
4590 observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
4591 return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
4592 };
4593
4594 /**
4595 * Invokes an action upon exceptional termination of the observable sequence.
4596 * 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.
4597 * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
4598 * @param {Any} [thisArg] Object to use as this when executing callback.
4599 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4600 */
4601 observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
4602 return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
4603 };
4604
4605 /**
4606 * Invokes an action upon graceful termination of the observable sequence.
4607 * 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.
4608 * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
4609 * @param {Any} [thisArg] Object to use as this when executing callback.
4610 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4611 */
4612 observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
4613 return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
4614 };
4615
4616 var FinallyObservable = (function (__super__) {
4617 inherits(FinallyObservable, __super__);
4618 function FinallyObservable(source, fn, thisArg) {
4619 this.source = source;
4620 this._fn = bindCallback(fn, thisArg, 0);
4621 __super__.call(this);
4622 }
4623
4624 FinallyObservable.prototype.subscribeCore = function (o) {
4625 var d = tryCatch(this.source.subscribe).call(this.source, o);
4626 if (d === errorObj) {
4627 this._fn();
4628 thrower(d.e);
4629 }
4630
4631 return new FinallyDisposable(d, this._fn);
4632 };
4633
4634 function FinallyDisposable(s, fn) {
4635 this.isDisposed = false;
4636 this._s = s;
4637 this._fn = fn;
4638 }
4639 FinallyDisposable.prototype.dispose = function () {
4640 if (!this.isDisposed) {
4641 var res = tryCatch(this._s.dispose).call(this._s);
4642 this._fn();
4643 res === errorObj && thrower(res.e);
4644 }
4645 };
4646
4647 return FinallyObservable;
4648
4649 }(ObservableBase));
4650
4651 /**
4652 * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
4653 * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
4654 * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
4655 */
4656 observableProto['finally'] = function (action, thisArg) {
4657 return new FinallyObservable(this, action, thisArg);
4658 };
4659
4660 var IgnoreElementsObservable = (function(__super__) {
4661 inherits(IgnoreElementsObservable, __super__);
4662
4663 function IgnoreElementsObservable(source) {
4664 this.source = source;
4665 __super__.call(this);
4666 }
4667
4668 IgnoreElementsObservable.prototype.subscribeCore = function (o) {
4669 return this.source.subscribe(new InnerObserver(o));
4670 };
4671
4672 function InnerObserver(o) {
4673 this.o = o;
4674 this.isStopped = false;
4675 }
4676 InnerObserver.prototype.onNext = noop;
4677 InnerObserver.prototype.onError = function (err) {
4678 if(!this.isStopped) {
4679 this.isStopped = true;
4680 this.o.onError(err);
4681 }
4682 };
4683 InnerObserver.prototype.onCompleted = function () {
4684 if(!this.isStopped) {
4685 this.isStopped = true;
4686 this.o.onCompleted();
4687 }
4688 };
4689 InnerObserver.prototype.dispose = function() { this.isStopped = true; };
4690 InnerObserver.prototype.fail = function (e) {
4691 if (!this.isStopped) {
4692 this.isStopped = true;
4693 this.observer.onError(e);
4694 return true;
4695 }
4696
4697 return false;
4698 };
4699
4700 return IgnoreElementsObservable;
4701 }(ObservableBase));
4702
4703 /**
4704 * Ignores all elements in an observable sequence leaving only the termination messages.
4705 * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
4706 */
4707 observableProto.ignoreElements = function () {
4708 return new IgnoreElementsObservable(this);
4709 };
4710
4711 var MaterializeObservable = (function (__super__) {
4712 inherits(MaterializeObservable, __super__);
4713 function MaterializeObservable(source, fn) {
4714 this.source = source;
4715 __super__.call(this);
4716 }
4717
4718 MaterializeObservable.prototype.subscribeCore = function (o) {
4719 return this.source.subscribe(new MaterializeObserver(o));
4720 };
4721
4722 return MaterializeObservable;
4723 }(ObservableBase));
4724
4725 var MaterializeObserver = (function (__super__) {
4726 inherits(MaterializeObserver, __super__);
4727
4728 function MaterializeObserver(o) {
4729 this._o = o;
4730 __super__.call(this);
4731 }
4732
4733 MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };
4734 MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };
4735 MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };
4736
4737 return MaterializeObserver;
4738 }(AbstractObserver));
4739
4740 /**
4741 * Materializes the implicit notifications of an observable sequence as explicit notification values.
4742 * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
4743 */
4744 observableProto.materialize = function () {
4745 return new MaterializeObservable(this);
4746 };
4747
4748 /**
4749 * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
4750 * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
4751 * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
4752 */
4753 observableProto.repeat = function (repeatCount) {
4754 return enumerableRepeat(this, repeatCount).concat();
4755 };
4756
4757 /**
4758 * 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.
4759 * Note if you encounter an error and want it to retry once, then you must use .retry(2);
4760 *
4761 * @example
4762 * var res = retried = retry.repeat();
4763 * var res = retried = retry.repeat(2);
4764 * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
4765 * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
4766 */
4767 observableProto.retry = function (retryCount) {
4768 return enumerableRepeat(this, retryCount).catchError();
4769 };
4770
4771 /**
4772 * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
4773 * if the notifier completes, the observable sequence completes.
4774 *
4775 * @example
4776 * var timer = Observable.timer(500);
4777 * var source = observable.retryWhen(timer);
4778 * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
4779 * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
4780 */
4781 observableProto.retryWhen = function (notifier) {
4782 return enumerableRepeat(this).catchErrorWhen(notifier);
4783 };
4784 var ScanObservable = (function(__super__) {
4785 inherits(ScanObservable, __super__);
4786 function ScanObservable(source, accumulator, hasSeed, seed) {
4787 this.source = source;
4788 this.accumulator = accumulator;
4789 this.hasSeed = hasSeed;
4790 this.seed = seed;
4791 __super__.call(this);
4792 }
4793
4794 ScanObservable.prototype.subscribeCore = function(o) {
4795 return this.source.subscribe(new ScanObserver(o,this));
4796 };
4797
4798 return ScanObservable;
4799 }(ObservableBase));
4800
4801 var ScanObserver = (function (__super__) {
4802 inherits(ScanObserver, __super__);
4803 function ScanObserver(o, parent) {
4804 this._o = o;
4805 this._p = parent;
4806 this._fn = parent.accumulator;
4807 this._hs = parent.hasSeed;
4808 this._s = parent.seed;
4809 this._ha = false;
4810 this._a = null;
4811 this._hv = false;
4812 this._i = 0;
4813 __super__.call(this);
4814 }
4815
4816 ScanObserver.prototype.next = function (x) {
4817 !this._hv && (this._hv = true);
4818 if (this._ha) {
4819 this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
4820 } else {
4821 this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
4822 this._ha = true;
4823 }
4824 if (this._a === errorObj) { return this._o.onError(this._a.e); }
4825 this._o.onNext(this._a);
4826 this._i++;
4827 };
4828
4829 ScanObserver.prototype.error = function (e) {
4830 this._o.onError(e);
4831 };
4832
4833 ScanObserver.prototype.completed = function () {
4834 !this._hv && this._hs && this._o.onNext(this._s);
4835 this._o.onCompleted();
4836 };
4837
4838 return ScanObserver;
4839 }(AbstractObserver));
4840
4841 /**
4842 * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
4843 * For aggregation behavior with no intermediate results, see Observable.aggregate.
4844 * @param {Mixed} [seed] The initial accumulator value.
4845 * @param {Function} accumulator An accumulator function to be invoked on each element.
4846 * @returns {Observable} An observable sequence containing the accumulated values.
4847 */
4848 observableProto.scan = function () {
4849 var hasSeed = false, seed, accumulator = arguments[0];
4850 if (arguments.length === 2) {
4851 hasSeed = true;
4852 seed = arguments[1];
4853 }
4854 return new ScanObservable(this, accumulator, hasSeed, seed);
4855 };
4856
4857 var SkipLastObservable = (function (__super__) {
4858 inherits(SkipLastObservable, __super__);
4859 function SkipLastObservable(source, c) {
4860 this.source = source;
4861 this._c = c;
4862 __super__.call(this);
4863 }
4864
4865 SkipLastObservable.prototype.subscribeCore = function (o) {
4866 return this.source.subscribe(new SkipLastObserver(o, this._c));
4867 };
4868
4869 return SkipLastObservable;
4870 }(ObservableBase));
4871
4872 var SkipLastObserver = (function (__super__) {
4873 inherits(SkipLastObserver, __super__);
4874 function SkipLastObserver(o, c) {
4875 this._o = o;
4876 this._c = c;
4877 this._q = [];
4878 __super__.call(this);
4879 }
4880
4881 SkipLastObserver.prototype.next = function (x) {
4882 this._q.push(x);
4883 this._q.length > this._c && this._o.onNext(this._q.shift());
4884 };
4885
4886 SkipLastObserver.prototype.error = function (e) {
4887 this._o.onError(e);
4888 };
4889
4890 SkipLastObserver.prototype.completed = function () {
4891 this._o.onCompleted();
4892 };
4893
4894 return SkipLastObserver;
4895 }(AbstractObserver));
4896
4897 /**
4898 * Bypasses a specified number of elements at the end of an observable sequence.
4899 * @description
4900 * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
4901 * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
4902 * @param count Number of elements to bypass at the end of the source sequence.
4903 * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
4904 */
4905 observableProto.skipLast = function (count) {
4906 if (count < 0) { throw new ArgumentOutOfRangeError(); }
4907 return new SkipLastObservable(this, count);
4908 };
4909
4910 /**
4911 * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
4912 * @example
4913 * var res = source.startWith(1, 2, 3);
4914 * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
4915 * @param {Arguments} args The specified values to prepend to the observable sequence
4916 * @returns {Observable} The source sequence prepended with the specified values.
4917 */
4918 observableProto.startWith = function () {
4919 var values, scheduler, start = 0;
4920 if (!!arguments.length && isScheduler(arguments[0])) {
4921 scheduler = arguments[0];
4922 start = 1;
4923 } else {
4924 scheduler = immediateScheduler;
4925 }
4926 for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
4927 return enumerableOf([observableFromArray(args, scheduler), this]).concat();
4928 };
4929
4930 var TakeLastObserver = (function (__super__) {
4931 inherits(TakeLastObserver, __super__);
4932 function TakeLastObserver(o, c) {
4933 this._o = o;
4934 this._c = c;
4935 this._q = [];
4936 __super__.call(this);
4937 }
4938
4939 TakeLastObserver.prototype.next = function (x) {
4940 this._q.push(x);
4941 this._q.length > this._c && this._q.shift();
4942 };
4943
4944 TakeLastObserver.prototype.error = function (e) {
4945 this._o.onError(e);
4946 };
4947
4948 TakeLastObserver.prototype.completed = function () {
4949 while (this._q.length > 0) { this._o.onNext(this._q.shift()); }
4950 this._o.onCompleted();
4951 };
4952
4953 return TakeLastObserver;
4954 }(AbstractObserver));
4955
4956 /**
4957 * Returns a specified number of contiguous elements from the end of an observable sequence.
4958 * @description
4959 * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
4960 * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
4961 * @param {Number} count Number of elements to take from the end of the source sequence.
4962 * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
4963 */
4964 observableProto.takeLast = function (count) {
4965 if (count < 0) { throw new ArgumentOutOfRangeError(); }
4966 var source = this;
4967 return new AnonymousObservable(function (o) {
4968 return source.subscribe(new TakeLastObserver(o, count));
4969 }, source);
4970 };
4971
4972 var TakeLastBufferObserver = (function (__super__) {
4973 inherits(TakeLastBufferObserver, __super__);
4974 function TakeLastBufferObserver(o, c) {
4975 this._o = o;
4976 this._c = c;
4977 this._q = [];
4978 __super__.call(this);
4979 }
4980
4981 TakeLastBufferObserver.prototype.next = function (x) {
4982 this._q.push(x);
4983 this._q.length > this._c && this._q.shift();
4984 };
4985
4986 TakeLastBufferObserver.prototype.error = function (e) {
4987 this._o.onError(e);
4988 };
4989
4990 TakeLastBufferObserver.prototype.completed = function () {
4991 this._o.onNext(this._q);
4992 this._o.onCompleted();
4993 };
4994
4995 return TakeLastBufferObserver;
4996 }(AbstractObserver));
4997
4998 /**
4999 * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
5000 *
5001 * @description
5002 * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
5003 * source sequence, this buffer is produced on the result sequence.
5004 * @param {Number} count Number of elements to take from the end of the source sequence.
5005 * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
5006 */
5007 observableProto.takeLastBuffer = function (count) {
5008 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5009 var source = this;
5010 return new AnonymousObservable(function (o) {
5011 return source.subscribe(new TakeLastBufferObserver(o, count));
5012 }, source);
5013 };
5014
5015 /**
5016 * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
5017 * @param {Number} count Length of each window.
5018 * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
5019 * @returns {Observable} An observable sequence of windows.
5020 */
5021 observableProto.windowWithCount = function (count, skip) {
5022 var source = this;
5023 +count || (count = 0);
5024 Math.abs(count) === Infinity && (count = 0);
5025 if (count <= 0) { throw new ArgumentOutOfRangeError(); }
5026 skip == null && (skip = count);
5027 +skip || (skip = 0);
5028 Math.abs(skip) === Infinity && (skip = 0);
5029
5030 if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
5031 return new AnonymousObservable(function (observer) {
5032 var m = new SingleAssignmentDisposable(),
5033 refCountDisposable = new RefCountDisposable(m),
5034 n = 0,
5035 q = [];
5036
5037 function createWindow () {
5038 var s = new Subject();
5039 q.push(s);
5040 observer.onNext(addRef(s, refCountDisposable));
5041 }
5042
5043 createWindow();
5044
5045 m.setDisposable(source.subscribe(
5046 function (x) {
5047 for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
5048 var c = n - count + 1;
5049 c >= 0 && c % skip === 0 && q.shift().onCompleted();
5050 ++n % skip === 0 && createWindow();
5051 },
5052 function (e) {
5053 while (q.length > 0) { q.shift().onError(e); }
5054 observer.onError(e);
5055 },
5056 function () {
5057 while (q.length > 0) { q.shift().onCompleted(); }
5058 observer.onCompleted();
5059 }
5060 ));
5061 return refCountDisposable;
5062 }, source);
5063 };
5064
5065observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) {
5066 return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1);
5067};
5068 /**
5069 * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
5070 * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
5071 * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
5072 * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
5073 * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
5074 * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
5075 */
5076 observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
5077 var source = this,
5078 onNextFunc = bindCallback(onNext, thisArg, 2),
5079 onErrorFunc = bindCallback(onError, thisArg, 1),
5080 onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
5081 return new AnonymousObservable(function (observer) {
5082 var index = 0;
5083 return source.subscribe(
5084 function (x) {
5085 var result;
5086 try {
5087 result = onNextFunc(x, index++);
5088 } catch (e) {
5089 observer.onError(e);
5090 return;
5091 }
5092 isPromise(result) && (result = observableFromPromise(result));
5093 observer.onNext(result);
5094 },
5095 function (err) {
5096 var result;
5097 try {
5098 result = onErrorFunc(err);
5099 } catch (e) {
5100 observer.onError(e);
5101 return;
5102 }
5103 isPromise(result) && (result = observableFromPromise(result));
5104 observer.onNext(result);
5105 observer.onCompleted();
5106 },
5107 function () {
5108 var result;
5109 try {
5110 result = onCompletedFunc();
5111 } catch (e) {
5112 observer.onError(e);
5113 return;
5114 }
5115 isPromise(result) && (result = observableFromPromise(result));
5116 observer.onNext(result);
5117 observer.onCompleted();
5118 });
5119 }, this).concatAll();
5120 };
5121
5122 var DefaultIfEmptyObserver = (function (__super__) {
5123 inherits(DefaultIfEmptyObserver, __super__);
5124 function DefaultIfEmptyObserver(o, d) {
5125 this._o = o;
5126 this._d = d;
5127 this._f = false;
5128 __super__.call(this);
5129 }
5130
5131 DefaultIfEmptyObserver.prototype.next = function (x) {
5132 this._f = true;
5133 this._o.onNext(x);
5134 };
5135
5136 DefaultIfEmptyObserver.prototype.error = function (e) {
5137 this._o.onError(e);
5138 };
5139
5140 DefaultIfEmptyObserver.prototype.completed = function () {
5141 !this._f && this._o.onNext(this._d);
5142 this._o.onCompleted();
5143 };
5144
5145 return DefaultIfEmptyObserver;
5146 }(AbstractObserver));
5147
5148 /**
5149 * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
5150 *
5151 * var res = obs = xs.defaultIfEmpty();
5152 * 2 - obs = xs.defaultIfEmpty(false);
5153 *
5154 * @memberOf Observable#
5155 * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
5156 * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
5157 */
5158 observableProto.defaultIfEmpty = function (defaultValue) {
5159 var source = this;
5160 defaultValue === undefined && (defaultValue = null);
5161 return new AnonymousObservable(function (o) {
5162 return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
5163 }, source);
5164 };
5165
5166 // Swap out for Array.findIndex
5167 function arrayIndexOfComparer(array, item, comparer) {
5168 for (var i = 0, len = array.length; i < len; i++) {
5169 if (comparer(array[i], item)) { return i; }
5170 }
5171 return -1;
5172 }
5173
5174 function HashSet(comparer) {
5175 this.comparer = comparer;
5176 this.set = [];
5177 }
5178 HashSet.prototype.push = function(value) {
5179 var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
5180 retValue && this.set.push(value);
5181 return retValue;
5182 };
5183
5184 var DistinctObservable = (function (__super__) {
5185 inherits(DistinctObservable, __super__);
5186 function DistinctObservable(source, keyFn, cmpFn) {
5187 this.source = source;
5188 this._keyFn = keyFn;
5189 this._cmpFn = cmpFn;
5190 __super__.call(this);
5191 }
5192
5193 DistinctObservable.prototype.subscribeCore = function (o) {
5194 return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
5195 };
5196
5197 return DistinctObservable;
5198 }(ObservableBase));
5199
5200 var DistinctObserver = (function (__super__) {
5201 inherits(DistinctObserver, __super__);
5202 function DistinctObserver(o, keyFn, cmpFn) {
5203 this._o = o;
5204 this._keyFn = keyFn;
5205 this._h = new HashSet(cmpFn);
5206 __super__.call(this);
5207 }
5208
5209 DistinctObserver.prototype.next = function (x) {
5210 var key = x;
5211 if (isFunction(this._keyFn)) {
5212 key = tryCatch(this._keyFn)(x);
5213 if (key === errorObj) { return this._o.onError(key.e); }
5214 }
5215 this._h.push(key) && this._o.onNext(x);
5216 };
5217
5218 DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
5219 DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
5220
5221 return DistinctObserver;
5222 }(AbstractObserver));
5223
5224 /**
5225 * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
5226 * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
5227 *
5228 * @example
5229 * var res = obs = xs.distinct();
5230 * 2 - obs = xs.distinct(function (x) { return x.id; });
5231 * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
5232 * @param {Function} [keySelector] A function to compute the comparison key for each element.
5233 * @param {Function} [comparer] Used to compare items in the collection.
5234 * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
5235 */
5236 observableProto.distinct = function (keySelector, comparer) {
5237 comparer || (comparer = defaultComparer);
5238 return new DistinctObservable(this, keySelector, comparer);
5239 };
5240
5241 var MapObservable = (function (__super__) {
5242 inherits(MapObservable, __super__);
5243
5244 function MapObservable(source, selector, thisArg) {
5245 this.source = source;
5246 this.selector = bindCallback(selector, thisArg, 3);
5247 __super__.call(this);
5248 }
5249
5250 function innerMap(selector, self) {
5251 return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };
5252 }
5253
5254 MapObservable.prototype.internalMap = function (selector, thisArg) {
5255 return new MapObservable(this.source, innerMap(selector, this), thisArg);
5256 };
5257
5258 MapObservable.prototype.subscribeCore = function (o) {
5259 return this.source.subscribe(new InnerObserver(o, this.selector, this));
5260 };
5261
5262 inherits(InnerObserver, AbstractObserver);
5263 function InnerObserver(o, selector, source) {
5264 this.o = o;
5265 this.selector = selector;
5266 this.source = source;
5267 this.i = 0;
5268 AbstractObserver.call(this);
5269 }
5270
5271 InnerObserver.prototype.next = function(x) {
5272 var result = tryCatch(this.selector)(x, this.i++, this.source);
5273 if (result === errorObj) { return this.o.onError(result.e); }
5274 this.o.onNext(result);
5275 };
5276
5277 InnerObserver.prototype.error = function (e) {
5278 this.o.onError(e);
5279 };
5280
5281 InnerObserver.prototype.completed = function () {
5282 this.o.onCompleted();
5283 };
5284
5285 return MapObservable;
5286
5287 }(ObservableBase));
5288
5289 /**
5290 * Projects each element of an observable sequence into a new form by incorporating the element's index.
5291 * @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.
5292 * @param {Any} [thisArg] Object to use as this when executing callback.
5293 * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
5294 */
5295 observableProto.map = observableProto.select = function (selector, thisArg) {
5296 var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
5297 return this instanceof MapObservable ?
5298 this.internalMap(selectorFn, thisArg) :
5299 new MapObservable(this, selectorFn, thisArg);
5300 };
5301
5302 function plucker(args, len) {
5303 return function mapper(x) {
5304 var currentProp = x;
5305 for (var i = 0; i < len; i++) {
5306 var p = currentProp[args[i]];
5307 if (typeof p !== 'undefined') {
5308 currentProp = p;
5309 } else {
5310 return undefined;
5311 }
5312 }
5313 return currentProp;
5314 }
5315 }
5316
5317 /**
5318 * Retrieves the value of a specified nested property from all elements in
5319 * the Observable sequence.
5320 * @param {Arguments} arguments The nested properties to pluck.
5321 * @returns {Observable} Returns a new Observable sequence of property values.
5322 */
5323 observableProto.pluck = function () {
5324 var len = arguments.length, args = new Array(len);
5325 if (len === 0) { throw new Error('List of properties cannot be empty.'); }
5326 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
5327 return this.map(plucker(args, len));
5328 };
5329
5330 /**
5331 * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
5332 * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
5333 * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
5334 * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
5335 * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
5336 * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
5337 */
5338 observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
5339 var source = this;
5340 return new AnonymousObservable(function (observer) {
5341 var index = 0;
5342
5343 return source.subscribe(
5344 function (x) {
5345 var result;
5346 try {
5347 result = onNext.call(thisArg, x, index++);
5348 } catch (e) {
5349 observer.onError(e);
5350 return;
5351 }
5352 isPromise(result) && (result = observableFromPromise(result));
5353 observer.onNext(result);
5354 },
5355 function (err) {
5356 var result;
5357 try {
5358 result = onError.call(thisArg, err);
5359 } catch (e) {
5360 observer.onError(e);
5361 return;
5362 }
5363 isPromise(result) && (result = observableFromPromise(result));
5364 observer.onNext(result);
5365 observer.onCompleted();
5366 },
5367 function () {
5368 var result;
5369 try {
5370 result = onCompleted.call(thisArg);
5371 } catch (e) {
5372 observer.onError(e);
5373 return;
5374 }
5375 isPromise(result) && (result = observableFromPromise(result));
5376 observer.onNext(result);
5377 observer.onCompleted();
5378 });
5379 }, source).mergeAll();
5380 };
5381
5382observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) {
5383 return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
5384};
5385
5386Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) {
5387 return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
5388};
5389 var SkipObservable = (function(__super__) {
5390 inherits(SkipObservable, __super__);
5391 function SkipObservable(source, count) {
5392 this.source = source;
5393 this._count = count;
5394 __super__.call(this);
5395 }
5396
5397 SkipObservable.prototype.subscribeCore = function (o) {
5398 return this.source.subscribe(new SkipObserver(o, this._count));
5399 };
5400
5401 function SkipObserver(o, c) {
5402 this._o = o;
5403 this._r = c;
5404 AbstractObserver.call(this);
5405 }
5406
5407 inherits(SkipObserver, AbstractObserver);
5408
5409 SkipObserver.prototype.next = function (x) {
5410 if (this._r <= 0) {
5411 this._o.onNext(x);
5412 } else {
5413 this._r--;
5414 }
5415 };
5416 SkipObserver.prototype.error = function(e) { this._o.onError(e); };
5417 SkipObserver.prototype.completed = function() { this._o.onCompleted(); };
5418
5419 return SkipObservable;
5420 }(ObservableBase));
5421
5422 /**
5423 * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
5424 * @param {Number} count The number of elements to skip before returning the remaining elements.
5425 * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
5426 */
5427 observableProto.skip = function (count) {
5428 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5429 return new SkipObservable(this, count);
5430 };
5431
5432 var SkipWhileObservable = (function (__super__) {
5433 inherits(SkipWhileObservable, __super__);
5434 function SkipWhileObservable(source, fn) {
5435 this.source = source;
5436 this._fn = fn;
5437 __super__.call(this);
5438 }
5439
5440 SkipWhileObservable.prototype.subscribeCore = function (o) {
5441 return this.source.subscribe(new SkipWhileObserver(o, this));
5442 };
5443
5444 return SkipWhileObservable;
5445 }(ObservableBase));
5446
5447 var SkipWhileObserver = (function (__super__) {
5448 inherits(SkipWhileObserver, __super__);
5449
5450 function SkipWhileObserver(o, p) {
5451 this._o = o;
5452 this._p = p;
5453 this._i = 0;
5454 this._r = false;
5455 __super__.call(this);
5456 }
5457
5458 SkipWhileObserver.prototype.next = function (x) {
5459 if (!this._r) {
5460 var res = tryCatch(this._p._fn)(x, this._i++, this._p);
5461 if (res === errorObj) { return this._o.onError(res.e); }
5462 this._r = !res;
5463 }
5464 this._r && this._o.onNext(x);
5465 };
5466 SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };
5467 SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
5468
5469 return SkipWhileObserver;
5470 }(AbstractObserver));
5471
5472 /**
5473 * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
5474 * The element's index is used in the logic of the predicate function.
5475 *
5476 * var res = source.skipWhile(function (value) { return value < 10; });
5477 * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
5478 * @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.
5479 * @param {Any} [thisArg] Object to use as this when executing callback.
5480 * @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.
5481 */
5482 observableProto.skipWhile = function (predicate, thisArg) {
5483 var fn = bindCallback(predicate, thisArg, 3);
5484 return new SkipWhileObservable(this, fn);
5485 };
5486
5487 var TakeObservable = (function(__super__) {
5488 inherits(TakeObservable, __super__);
5489 function TakeObservable(source, count) {
5490 this.source = source;
5491 this._count = count;
5492 __super__.call(this);
5493 }
5494
5495 TakeObservable.prototype.subscribeCore = function (o) {
5496 return this.source.subscribe(new TakeObserver(o, this._count));
5497 };
5498
5499 function TakeObserver(o, c) {
5500 this._o = o;
5501 this._c = c;
5502 this._r = c;
5503 AbstractObserver.call(this);
5504 }
5505
5506 inherits(TakeObserver, AbstractObserver);
5507
5508 TakeObserver.prototype.next = function (x) {
5509 if (this._r-- > 0) {
5510 this._o.onNext(x);
5511 this._r <= 0 && this._o.onCompleted();
5512 }
5513 };
5514
5515 TakeObserver.prototype.error = function (e) { this._o.onError(e); };
5516 TakeObserver.prototype.completed = function () { this._o.onCompleted(); };
5517
5518 return TakeObservable;
5519 }(ObservableBase));
5520
5521 /**
5522 * 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).
5523 * @param {Number} count The number of elements to return.
5524 * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
5525 * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
5526 */
5527 observableProto.take = function (count, scheduler) {
5528 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5529 if (count === 0) { return observableEmpty(scheduler); }
5530 return new TakeObservable(this, count);
5531 };
5532
5533 var TakeWhileObservable = (function (__super__) {
5534 inherits(TakeWhileObservable, __super__);
5535 function TakeWhileObservable(source, fn) {
5536 this.source = source;
5537 this._fn = fn;
5538 __super__.call(this);
5539 }
5540
5541 TakeWhileObservable.prototype.subscribeCore = function (o) {
5542 return this.source.subscribe(new TakeWhileObserver(o, this));
5543 };
5544
5545 return TakeWhileObservable;
5546 }(ObservableBase));
5547
5548 var TakeWhileObserver = (function (__super__) {
5549 inherits(TakeWhileObserver, __super__);
5550
5551 function TakeWhileObserver(o, p) {
5552 this._o = o;
5553 this._p = p;
5554 this._i = 0;
5555 this._r = true;
5556 __super__.call(this);
5557 }
5558
5559 TakeWhileObserver.prototype.next = function (x) {
5560 if (this._r) {
5561 this._r = tryCatch(this._p._fn)(x, this._i++, this._p);
5562 if (this._r === errorObj) { return this._o.onError(this._r.e); }
5563 }
5564 if (this._r) {
5565 this._o.onNext(x);
5566 } else {
5567 this._o.onCompleted();
5568 }
5569 };
5570 TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };
5571 TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
5572
5573 return TakeWhileObserver;
5574 }(AbstractObserver));
5575
5576 /**
5577 * Returns elements from an observable sequence as long as a specified condition is true.
5578 * The element's index is used in the logic of the predicate function.
5579 * @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.
5580 * @param {Any} [thisArg] Object to use as this when executing callback.
5581 * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
5582 */
5583 observableProto.takeWhile = function (predicate, thisArg) {
5584 var fn = bindCallback(predicate, thisArg, 3);
5585 return new TakeWhileObservable(this, fn);
5586 };
5587
5588 var FilterObservable = (function (__super__) {
5589 inherits(FilterObservable, __super__);
5590
5591 function FilterObservable(source, predicate, thisArg) {
5592 this.source = source;
5593 this.predicate = bindCallback(predicate, thisArg, 3);
5594 __super__.call(this);
5595 }
5596
5597 FilterObservable.prototype.subscribeCore = function (o) {
5598 return this.source.subscribe(new InnerObserver(o, this.predicate, this));
5599 };
5600
5601 function innerPredicate(predicate, self) {
5602 return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
5603 }
5604
5605 FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
5606 return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
5607 };
5608
5609 inherits(InnerObserver, AbstractObserver);
5610 function InnerObserver(o, predicate, source) {
5611 this.o = o;
5612 this.predicate = predicate;
5613 this.source = source;
5614 this.i = 0;
5615 AbstractObserver.call(this);
5616 }
5617
5618 InnerObserver.prototype.next = function(x) {
5619 var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
5620 if (shouldYield === errorObj) {
5621 return this.o.onError(shouldYield.e);
5622 }
5623 shouldYield && this.o.onNext(x);
5624 };
5625
5626 InnerObserver.prototype.error = function (e) {
5627 this.o.onError(e);
5628 };
5629
5630 InnerObserver.prototype.completed = function () {
5631 this.o.onCompleted();
5632 };
5633
5634 return FilterObservable;
5635
5636 }(ObservableBase));
5637
5638 /**
5639 * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
5640 * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
5641 * @param {Any} [thisArg] Object to use as this when executing callback.
5642 * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
5643 */
5644 observableProto.filter = observableProto.where = function (predicate, thisArg) {
5645 return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
5646 new FilterObservable(this, predicate, thisArg);
5647 };
5648
5649 var TransduceObserver = (function (__super__) {
5650 inherits(TransduceObserver, __super__);
5651 function TransduceObserver(o, xform) {
5652 this._o = o;
5653 this._xform = xform;
5654 __super__.call(this);
5655 }
5656
5657 TransduceObserver.prototype.next = function (x) {
5658 var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x);
5659 if (res === errorObj) { this._o.onError(res.e); }
5660 };
5661
5662 TransduceObserver.prototype.error = function (e) { this._o.onError(e); };
5663
5664 TransduceObserver.prototype.completed = function () {
5665 this._xform['@@transducer/result'](this._o);
5666 };
5667
5668 return TransduceObserver;
5669 }(AbstractObserver));
5670
5671 function transformForObserver(o) {
5672 return {
5673 '@@transducer/init': function() {
5674 return o;
5675 },
5676 '@@transducer/step': function(obs, input) {
5677 return obs.onNext(input);
5678 },
5679 '@@transducer/result': function(obs) {
5680 return obs.onCompleted();
5681 }
5682 };
5683 }
5684
5685 /**
5686 * Executes a transducer to transform the observable sequence
5687 * @param {Transducer} transducer A transducer to execute
5688 * @returns {Observable} An Observable sequence containing the results from the transducer.
5689 */
5690 observableProto.transduce = function(transducer) {
5691 var source = this;
5692 return new AnonymousObservable(function(o) {
5693 var xform = transducer(transformForObserver(o));
5694 return source.subscribe(new TransduceObserver(o, xform));
5695 }, source);
5696 };
5697
5698 var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
5699 inherits(AnonymousObservable, __super__);
5700
5701 // Fix subscriber to check for undefined or function returned to decorate as Disposable
5702 function fixSubscriber(subscriber) {
5703 return subscriber && isFunction(subscriber.dispose) ? subscriber :
5704 isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
5705 }
5706
5707 function setDisposable(s, state) {
5708 var ado = state[0], self = state[1];
5709 var sub = tryCatch(self.__subscribe).call(self, ado);
5710 if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
5711 ado.setDisposable(fixSubscriber(sub));
5712 }
5713
5714 function AnonymousObservable(subscribe, parent) {
5715 this.source = parent;
5716 this.__subscribe = subscribe;
5717 __super__.call(this);
5718 }
5719
5720 AnonymousObservable.prototype._subscribe = function (o) {
5721 var ado = new AutoDetachObserver(o), state = [ado, this];
5722
5723 if (currentThreadScheduler.scheduleRequired()) {
5724 currentThreadScheduler.schedule(state, setDisposable);
5725 } else {
5726 setDisposable(null, state);
5727 }
5728 return ado;
5729 };
5730
5731 return AnonymousObservable;
5732
5733 }(Observable));
5734
5735 var AutoDetachObserver = (function (__super__) {
5736 inherits(AutoDetachObserver, __super__);
5737
5738 function AutoDetachObserver(observer) {
5739 __super__.call(this);
5740 this.observer = observer;
5741 this.m = new SingleAssignmentDisposable();
5742 }
5743
5744 var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
5745
5746 AutoDetachObserverPrototype.next = function (value) {
5747 var result = tryCatch(this.observer.onNext).call(this.observer, value);
5748 if (result === errorObj) {
5749 this.dispose();
5750 thrower(result.e);
5751 }
5752 };
5753
5754 AutoDetachObserverPrototype.error = function (err) {
5755 var result = tryCatch(this.observer.onError).call(this.observer, err);
5756 this.dispose();
5757 result === errorObj && thrower(result.e);
5758 };
5759
5760 AutoDetachObserverPrototype.completed = function () {
5761 var result = tryCatch(this.observer.onCompleted).call(this.observer);
5762 this.dispose();
5763 result === errorObj && thrower(result.e);
5764 };
5765
5766 AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
5767 AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
5768
5769 AutoDetachObserverPrototype.dispose = function () {
5770 __super__.prototype.dispose.call(this);
5771 this.m.dispose();
5772 };
5773
5774 return AutoDetachObserver;
5775 }(AbstractObserver));
5776
5777 var InnerSubscription = function (s, o) {
5778 this._s = s;
5779 this._o = o;
5780 };
5781
5782 InnerSubscription.prototype.dispose = function () {
5783 if (!this._s.isDisposed && this._o !== null) {
5784 var idx = this._s.observers.indexOf(this._o);
5785 this._s.observers.splice(idx, 1);
5786 this._o = null;
5787 }
5788 };
5789
5790 /**
5791 * Represents an object that is both an observable sequence as well as an observer.
5792 * Each notification is broadcasted to all subscribed observers.
5793 */
5794 var Subject = Rx.Subject = (function (__super__) {
5795 inherits(Subject, __super__);
5796 function Subject() {
5797 __super__.call(this);
5798 this.isDisposed = false;
5799 this.isStopped = false;
5800 this.observers = [];
5801 this.hasError = false;
5802 }
5803
5804 addProperties(Subject.prototype, Observer.prototype, {
5805 _subscribe: function (o) {
5806 checkDisposed(this);
5807 if (!this.isStopped) {
5808 this.observers.push(o);
5809 return new InnerSubscription(this, o);
5810 }
5811 if (this.hasError) {
5812 o.onError(this.error);
5813 return disposableEmpty;
5814 }
5815 o.onCompleted();
5816 return disposableEmpty;
5817 },
5818 /**
5819 * Indicates whether the subject has observers subscribed to it.
5820 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
5821 */
5822 hasObservers: function () { return this.observers.length > 0; },
5823 /**
5824 * Notifies all subscribed observers about the end of the sequence.
5825 */
5826 onCompleted: function () {
5827 checkDisposed(this);
5828 if (!this.isStopped) {
5829 this.isStopped = true;
5830 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
5831 os[i].onCompleted();
5832 }
5833
5834 this.observers.length = 0;
5835 }
5836 },
5837 /**
5838 * Notifies all subscribed observers about the exception.
5839 * @param {Mixed} error The exception to send to all observers.
5840 */
5841 onError: function (error) {
5842 checkDisposed(this);
5843 if (!this.isStopped) {
5844 this.isStopped = true;
5845 this.error = error;
5846 this.hasError = true;
5847 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
5848 os[i].onError(error);
5849 }
5850
5851 this.observers.length = 0;
5852 }
5853 },
5854 /**
5855 * Notifies all subscribed observers about the arrival of the specified element in the sequence.
5856 * @param {Mixed} value The value to send to all observers.
5857 */
5858 onNext: function (value) {
5859 checkDisposed(this);
5860 if (!this.isStopped) {
5861 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
5862 os[i].onNext(value);
5863 }
5864 }
5865 },
5866 /**
5867 * Unsubscribe all observers and release resources.
5868 */
5869 dispose: function () {
5870 this.isDisposed = true;
5871 this.observers = null;
5872 }
5873 });
5874
5875 /**
5876 * Creates a subject from the specified observer and observable.
5877 * @param {Observer} observer The observer used to send messages to the subject.
5878 * @param {Observable} observable The observable used to subscribe to messages sent from the subject.
5879 * @returns {Subject} Subject implemented using the given observer and observable.
5880 */
5881 Subject.create = function (observer, observable) {
5882 return new AnonymousSubject(observer, observable);
5883 };
5884
5885 return Subject;
5886 }(Observable));
5887
5888 /**
5889 * Represents the result of an asynchronous operation.
5890 * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
5891 */
5892 var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
5893 inherits(AsyncSubject, __super__);
5894
5895 /**
5896 * Creates a subject that can only receive one value and that value is cached for all future observations.
5897 * @constructor
5898 */
5899 function AsyncSubject() {
5900 __super__.call(this);
5901 this.isDisposed = false;
5902 this.isStopped = false;
5903 this.hasValue = false;
5904 this.observers = [];
5905 this.hasError = false;
5906 }
5907
5908 addProperties(AsyncSubject.prototype, Observer.prototype, {
5909 _subscribe: function (o) {
5910 checkDisposed(this);
5911
5912 if (!this.isStopped) {
5913 this.observers.push(o);
5914 return new InnerSubscription(this, o);
5915 }
5916
5917 if (this.hasError) {
5918 o.onError(this.error);
5919 } else if (this.hasValue) {
5920 o.onNext(this.value);
5921 o.onCompleted();
5922 } else {
5923 o.onCompleted();
5924 }
5925
5926 return disposableEmpty;
5927 },
5928 /**
5929 * Indicates whether the subject has observers subscribed to it.
5930 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
5931 */
5932 hasObservers: function () {
5933 checkDisposed(this);
5934 return this.observers.length > 0;
5935 },
5936 /**
5937 * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
5938 */
5939 onCompleted: function () {
5940 var i, len;
5941 checkDisposed(this);
5942 if (!this.isStopped) {
5943 this.isStopped = true;
5944 var os = cloneArray(this.observers), len = os.length;
5945
5946 if (this.hasValue) {
5947 for (i = 0; i < len; i++) {
5948 var o = os[i];
5949 o.onNext(this.value);
5950 o.onCompleted();
5951 }
5952 } else {
5953 for (i = 0; i < len; i++) {
5954 os[i].onCompleted();
5955 }
5956 }
5957
5958 this.observers.length = 0;
5959 }
5960 },
5961 /**
5962 * Notifies all subscribed observers about the error.
5963 * @param {Mixed} error The Error to send to all observers.
5964 */
5965 onError: function (error) {
5966 checkDisposed(this);
5967 if (!this.isStopped) {
5968 this.isStopped = true;
5969 this.hasError = true;
5970 this.error = error;
5971
5972 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
5973 os[i].onError(error);
5974 }
5975
5976 this.observers.length = 0;
5977 }
5978 },
5979 /**
5980 * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
5981 * @param {Mixed} value The value to store in the subject.
5982 */
5983 onNext: function (value) {
5984 checkDisposed(this);
5985 if (this.isStopped) { return; }
5986 this.value = value;
5987 this.hasValue = true;
5988 },
5989 /**
5990 * Unsubscribe all observers and release resources.
5991 */
5992 dispose: function () {
5993 this.isDisposed = true;
5994 this.observers = null;
5995 this.error = null;
5996 this.value = null;
5997 }
5998 });
5999
6000 return AsyncSubject;
6001 }(Observable));
6002
6003 var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
6004 inherits(AnonymousSubject, __super__);
6005 function AnonymousSubject(observer, observable) {
6006 this.observer = observer;
6007 this.observable = observable;
6008 __super__.call(this);
6009 }
6010
6011 addProperties(AnonymousSubject.prototype, Observer.prototype, {
6012 _subscribe: function (o) {
6013 return this.observable.subscribe(o);
6014 },
6015 onCompleted: function () {
6016 this.observer.onCompleted();
6017 },
6018 onError: function (error) {
6019 this.observer.onError(error);
6020 },
6021 onNext: function (value) {
6022 this.observer.onNext(value);
6023 }
6024 });
6025
6026 return AnonymousSubject;
6027 }(Observable));
6028
6029 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
6030 root.Rx = Rx;
6031
6032 define(function() {
6033 return Rx;
6034 });
6035 } else if (freeExports && freeModule) {
6036 // in Node.js or RingoJS
6037 if (moduleExports) {
6038 (freeModule.exports = Rx).Rx = Rx;
6039 } else {
6040 freeExports.Rx = Rx;
6041 }
6042 } else {
6043 // in a browser or Rhino
6044 root.Rx = Rx;
6045 }
6046
6047 // All code before this point will be filtered from stack traces.
6048 var rEndingLine = captureLine();
6049
6050}.call(this));