UNPKG

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