UNPKG

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