UNPKG

438 kBJavaScriptView Raw
1// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
2
3;(function (undefined) {
4
5 var objectTypes = {
6 'function': true,
7 'object': true
8 };
9
10 function checkGlobal(value) {
11 return (value && value.Object === Object) ? value : null;
12 }
13
14 var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
15 var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
16 var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
17 var freeSelf = checkGlobal(objectTypes[typeof self] && self);
18 var freeWindow = checkGlobal(objectTypes[typeof window] && window);
19 var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
20 var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
21 var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
22
23 var Rx = {
24 internals: {},
25 config: {
26 Promise: root.Promise
27 },
28 helpers: { }
29 };
30
31 // Defaults
32 var noop = Rx.helpers.noop = function () { },
33 identity = Rx.helpers.identity = function (x) { return x; },
34 defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
35 defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
36 defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
37 defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
38 defaultError = Rx.helpers.defaultError = function (err) { throw err; },
39 isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
40 isFunction = Rx.helpers.isFunction = (function () {
41 var isFn = function (value) {
42 return typeof value == 'function' || false;
43 };
44
45 // fallback for older versions of Chrome and Safari
46 if (isFn(/x/)) {
47 isFn = function(value) {
48 return typeof value == 'function' && toString.call(value) == '[object Function]';
49 };
50 }
51 return isFn;
52 }());
53
54 function cloneArray(arr) {
55 var len = arr.length, a = new Array(len);
56 for(var i = 0; i < len; i++) { a[i] = arr[i]; }
57 return a;
58 }
59
60 var errorObj = {e: {}};
61
62 function tryCatcherGen(tryCatchTarget) {
63 return function tryCatcher() {
64 try {
65 return tryCatchTarget.apply(this, arguments);
66 } catch (e) {
67 errorObj.e = e;
68 return errorObj;
69 }
70 };
71 }
72
73 var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
74 if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
75 return tryCatcherGen(fn);
76 };
77
78 function thrower(e) {
79 throw e;
80 }
81
82 Rx.config.longStackSupport = false;
83 var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
84 hasStacks = !!stacks.e && !!stacks.e.stack;
85
86 // All code after this point will be filtered from stack traces reported by RxJS
87 var rStartingLine = captureLine(), rFileName;
88
89 var STACK_JUMP_SEPARATOR = 'From previous event:';
90
91 function makeStackTraceLong(error, observable) {
92 // If possible, transform the error stack trace by removing Node and RxJS
93 // cruft, then concatenating with the stack trace of `observable`.
94 if (hasStacks &&
95 observable.stack &&
96 typeof error === 'object' &&
97 error !== null &&
98 error.stack &&
99 error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
100 ) {
101 var stacks = [];
102 for (var o = observable; !!o; o = o.source) {
103 if (o.stack) {
104 stacks.unshift(o.stack);
105 }
106 }
107 stacks.unshift(error.stack);
108
109 var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
110 error.stack = filterStackString(concatedStacks);
111 }
112 }
113
114 function filterStackString(stackString) {
115 var lines = stackString.split('\n'), desiredLines = [];
116 for (var i = 0, len = lines.length; i < len; i++) {
117 var line = lines[i];
118
119 if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
120 desiredLines.push(line);
121 }
122 }
123 return desiredLines.join('\n');
124 }
125
126 function isInternalFrame(stackLine) {
127 var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
128 if (!fileNameAndLineNumber) {
129 return false;
130 }
131 var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
132
133 return fileName === rFileName &&
134 lineNumber >= rStartingLine &&
135 lineNumber <= rEndingLine;
136 }
137
138 function isNodeFrame(stackLine) {
139 return stackLine.indexOf('(module.js:') !== -1 ||
140 stackLine.indexOf('(node.js:') !== -1;
141 }
142
143 function captureLine() {
144 if (!hasStacks) { return; }
145
146 try {
147 throw new Error();
148 } catch (e) {
149 var lines = e.stack.split('\n');
150 var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
151 var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
152 if (!fileNameAndLineNumber) { return; }
153
154 rFileName = fileNameAndLineNumber[0];
155 return fileNameAndLineNumber[1];
156 }
157 }
158
159 function getFileNameAndLineNumber(stackLine) {
160 // Named functions: 'at functionName (filename:lineNumber:columnNumber)'
161 var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
162 if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
163
164 // Anonymous functions: 'at filename:lineNumber:columnNumber'
165 var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
166 if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
167
168 // Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
169 var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
170 if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
171 }
172
173 // Utilities
174 var toString = Object.prototype.toString;
175
176 if (!Array.prototype.forEach) {
177 Array.prototype.forEach = function (callback, thisArg) {
178 var T, k;
179
180 if (this == null) {
181 throw new TypeError(' this is null or not defined');
182 }
183
184 var O = Object(this);
185 var len = O.length >>> 0;
186
187 if (typeof callback !== 'function') {
188 throw new TypeError(callback + ' is not a function');
189 }
190
191 if (arguments.length > 1) {
192 T = thisArg;
193 }
194
195 k = 0;
196 while (k < len) {
197 var kValue;
198 if (k in O) {
199 kValue = O[k];
200 callback.call(T, kValue, k, O);
201 }
202 k++;
203 }
204 };
205 }
206
207 var boxedString = Object('a'),
208 splitString = boxedString[0] !== 'a' || !(0 in boxedString);
209 if (!Array.prototype.every) {
210 Array.prototype.every = function every(fun /*, thisp */) {
211 var object = Object(this),
212 self = splitString && toString.call(this) === stringClass ?
213 this.split('') :
214 object,
215 length = self.length >>> 0,
216 thisp = arguments[1];
217
218 if (toString.call(fun) !== funcClass) {
219 throw new TypeError(fun + ' is not a function');
220 }
221
222 for (var i = 0; i < length; i++) {
223 if (i in self && !fun.call(thisp, self[i], i, object)) {
224 return false;
225 }
226 }
227 return true;
228 };
229 }
230
231 if (!Array.prototype.map) {
232 Array.prototype.map = function map(fun /*, thisp*/) {
233 var object = Object(this),
234 self = splitString && toString.call(this) === stringClass ?
235 this.split('') :
236 object,
237 length = self.length >>> 0,
238 result = new Array(length),
239 thisp = arguments[1];
240
241 if (toString.call(fun) !== funcClass) {
242 throw new TypeError(fun + ' is not a function');
243 }
244
245 for (var i = 0; i < length; i++) {
246 if (i in self) {
247 result[i] = fun.call(thisp, self[i], i, object);
248 }
249 }
250 return result;
251 };
252 }
253
254 if (!Array.prototype.filter) {
255 Array.prototype.filter = function (predicate) {
256 var results = [], item, t = new Object(this);
257 for (var i = 0, len = t.length >>> 0; i < len; i++) {
258 item = t[i];
259 if (i in t && predicate.call(arguments[1], item, i, t)) {
260 results.push(item);
261 }
262 }
263 return results;
264 };
265 }
266
267 if (!Array.isArray) {
268 Array.isArray = function (arg) {
269 return toString.call(arg) === arrayClass;
270 };
271 }
272
273 if (!Array.prototype.indexOf) {
274 Array.prototype.indexOf = function indexOf(searchElement) {
275 var t = Object(this);
276 var len = t.length >>> 0;
277 if (len === 0) {
278 return -1;
279 }
280 var n = 0;
281 if (arguments.length > 1) {
282 n = Number(arguments[1]);
283 if (n !== n) {
284 n = 0;
285 } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
286 n = (n > 0 || -1) * Math.floor(Math.abs(n));
287 }
288 }
289 if (n >= len) {
290 return -1;
291 }
292 var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
293 for (; k < len; k++) {
294 if (k in t && t[k] === searchElement) {
295 return k;
296 }
297 }
298 return -1;
299 };
300 }
301
302 // Fix for Tessel
303 if (!Object.prototype.propertyIsEnumerable) {
304 Object.prototype.propertyIsEnumerable = function (key) {
305 for (var k in this) { if (k === key) { return true; } }
306 return false;
307 };
308 }
309
310 if (!Object.keys) {
311 Object.keys = (function() {
312 'use strict';
313 var hasOwnProperty = Object.prototype.hasOwnProperty,
314 hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
315
316 return function(obj) {
317 if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
318 throw new TypeError('Object.keys called on non-object');
319 }
320
321 var result = [], prop, i;
322
323 for (prop in obj) {
324 if (hasOwnProperty.call(obj, prop)) {
325 result.push(prop);
326 }
327 }
328
329 if (hasDontEnumBug) {
330 for (i = 0; i < dontEnumsLength; i++) {
331 if (hasOwnProperty.call(obj, dontEnums[i])) {
332 result.push(dontEnums[i]);
333 }
334 }
335 }
336 return result;
337 };
338 }());
339 }
340
341 if (typeof Object.create !== 'function') {
342 // Production steps of ECMA-262, Edition 5, 15.2.3.5
343 // Reference: http://es5.github.io/#x15.2.3.5
344 Object.create = (function() {
345 function Temp() {}
346
347 var hasOwn = Object.prototype.hasOwnProperty;
348
349 return function (O) {
350 if (typeof O !== 'object') {
351 throw new TypeError('Object prototype may only be an Object or null');
352 }
353
354 Temp.prototype = O;
355 var obj = new Temp();
356 Temp.prototype = null;
357
358 if (arguments.length > 1) {
359 // Object.defineProperties does ToObject on its first argument.
360 var Properties = Object(arguments[1]);
361 for (var prop in Properties) {
362 if (hasOwn.call(Properties, prop)) {
363 obj[prop] = Properties[prop];
364 }
365 }
366 }
367
368 // 5. Return obj
369 return obj;
370 };
371 })();
372 }
373
374 root.Element && root.Element.prototype.attachEvent && !root.Element.prototype.addEventListener && (function () {
375 function addMethod(name, fn) {
376 Window.prototype[name] = HTMLDocument.prototype[name] = Element.prototype[name] = fn;
377 }
378
379 addMethod('addEventListener', function (type, listener) {
380 var target = this;
381 var listeners = target._c1_listeners = target._c1_listeners || {};
382 var typeListeners = listeners[type] = listeners[type] || [];
383
384 target.attachEvent('on' + type, typeListeners.event = function (e) {
385 e || (e = root.event);
386
387 var documentElement = target.document &&
388 target.document.documentElement ||
389 target.documentElement ||
390 { scrollLeft: 0, scrollTop: 0 };
391
392 e.currentTarget = target;
393 e.pageX = e.clientX + documentElement.scrollLeft;
394 e.pageY = e.clientY + documentElement.scrollTop;
395
396 e.preventDefault = function () {
397 e.bubbledKeyCode = e.keyCode;
398 if (e.ctrlKey) {
399 try {
400 e.keyCode = 0;
401 } catch (e) { }
402 }
403 e.defaultPrevented = true;
404 e.returnValue = false;
405 e.modified = true;
406 e.returnValue = false;
407 };
408
409 e.stopImmediatePropagation = function () {
410 immediatePropagation = false;
411 e.cancelBubble = true;
412 };
413
414 e.stopPropagation = function () {
415 e.cancelBubble = true;
416 };
417
418 e.relatedTarget = e.fromElement || null;
419 e.target = e.srcElement || target;
420 e.timeStamp = +new Date();
421
422 // Normalize key events
423 switch(e.type) {
424 case 'keypress':
425 var c = ('charCode' in e ? e.charCode : e.keyCode);
426 if (c === 10) {
427 c = 0;
428 e.keyCode = 13;
429 } else if (c === 13 || c === 27) {
430 c = 0;
431 } else if (c === 3) {
432 c = 99;
433 }
434 e.charCode = c;
435 e.keyChar = e.charCode ? String.fromCharCode(e.charCode) : '';
436 break;
437 }
438
439 var copiedEvent = {};
440 for (var prop in e) {
441 copiedEvent[prop] = e[prop];
442 }
443
444 for (var i = 0, typeListenersCache = [].concat(typeListeners), typeListenerCache, immediatePropagation = true; immediatePropagation && (typeListenerCache = typeListenersCache[i]); ++i) {
445 for (var ii = 0, typeListener; typeListener = typeListeners[ii]; ++ii) {
446 if (typeListener === typeListenerCache) { typeListener.call(target, copiedEvent); break; }
447 }
448 }
449 });
450
451 typeListeners.push(listener);
452 });
453
454 addMethod('removeEventListener', function (type, listener) {
455 var target = this;
456 var listeners = target._c1_listeners = target._c1_listeners || {};
457 var typeListeners = listeners[type] = listeners[type] || [];
458
459 for (var i = typeListeners.length - 1, typeListener; typeListener = typeListeners[i]; --i) {
460 if (typeListener === listener) { typeListeners.splice(i, 1); break; }
461 }
462
463 !typeListeners.length &&
464 typeListeners.event &&
465 target.detachEvent('on' + type, typeListeners.event);
466 });
467
468 addMethod('dispatchEvent', function (e) {
469 var target = this;
470 var type = e.type;
471 var listeners = target._c1_listeners = target._c1_listeners || {};
472 var typeListeners = listeners[type] = listeners[type] || [];
473
474 try {
475 return target.fireEvent('on' + type, e);
476 } catch (err) {
477 return typeListeners.event && typeListeners.event(e);
478 }
479 });
480
481 function ready() {
482 if (ready.interval && document.body) {
483 ready.interval = clearInterval(ready.interval);
484
485 document.dispatchEvent(new CustomEvent('DOMContentLoaded'));
486 }
487 }
488
489 ready.interval = setInterval(ready, 1);
490
491 root.addEventListener('load', ready);
492 }());
493
494 (!root.CustomEvent || typeof root.CustomEvent === 'object') && (function() {
495 function CustomEvent (type, params) {
496 var event;
497 params = params || { bubbles: false, cancelable: false, detail: undefined };
498
499 try {
500 if (document.createEvent) {
501 event = document.createEvent('CustomEvent');
502 event.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
503 } else if (document.createEventObject) {
504 event = document.createEventObject();
505 }
506 } catch (error) {
507 event = document.createEvent('Event');
508 event.initEvent(type, params.bubbles, params.cancelable);
509 event.detail = params.detail;
510 }
511
512 return event;
513 }
514
515 root.CustomEvent && (CustomEvent.prototype = root.CustomEvent.prototype);
516 root.CustomEvent = CustomEvent;
517 }());
518
519 var EmptyError = Rx.EmptyError = function() {
520 this.message = 'Sequence contains no elements.';
521 Error.call(this);
522 };
523 EmptyError.prototype = Object.create(Error.prototype);
524 EmptyError.prototype.name = 'EmptyError';
525
526 var ObjectDisposedError = Rx.ObjectDisposedError = function() {
527 this.message = 'Object has been disposed';
528 Error.call(this);
529 };
530 ObjectDisposedError.prototype = Object.create(Error.prototype);
531 ObjectDisposedError.prototype.name = 'ObjectDisposedError';
532
533 var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
534 this.message = 'Argument out of range';
535 Error.call(this);
536 };
537 ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
538 ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';
539
540 var NotSupportedError = Rx.NotSupportedError = function (message) {
541 this.message = message || 'This operation is not supported';
542 Error.call(this);
543 };
544 NotSupportedError.prototype = Object.create(Error.prototype);
545 NotSupportedError.prototype.name = 'NotSupportedError';
546
547 var NotImplementedError = Rx.NotImplementedError = function (message) {
548 this.message = message || 'This operation is not implemented';
549 Error.call(this);
550 };
551 NotImplementedError.prototype = Object.create(Error.prototype);
552 NotImplementedError.prototype.name = 'NotImplementedError';
553
554 var notImplemented = Rx.helpers.notImplemented = function () {
555 throw new NotImplementedError();
556 };
557
558 var notSupported = Rx.helpers.notSupported = function () {
559 throw new NotSupportedError();
560 };
561
562 // Shim in iterator support
563 var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
564 '_es6shim_iterator_';
565 // Bug for mozilla version
566 if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
567 $iterator$ = '@@iterator';
568 }
569
570 var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
571
572 var isIterable = Rx.helpers.isIterable = function (o) {
573 return o && o[$iterator$] !== undefined;
574 };
575
576 var isArrayLike = Rx.helpers.isArrayLike = function (o) {
577 return o && o.length !== undefined;
578 };
579
580 Rx.helpers.iterator = $iterator$;
581
582 var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
583 if (typeof thisArg === 'undefined') { return func; }
584 switch(argCount) {
585 case 0:
586 return function() {
587 return func.call(thisArg)
588 };
589 case 1:
590 return function(arg) {
591 return func.call(thisArg, arg);
592 };
593 case 2:
594 return function(value, index) {
595 return func.call(thisArg, value, index);
596 };
597 case 3:
598 return function(value, index, collection) {
599 return func.call(thisArg, value, index, collection);
600 };
601 }
602
603 return function() {
604 return func.apply(thisArg, arguments);
605 };
606 };
607
608 /** Used to determine if values are of the language type Object */
609 var dontEnums = ['toString',
610 'toLocaleString',
611 'valueOf',
612 'hasOwnProperty',
613 'isPrototypeOf',
614 'propertyIsEnumerable',
615 'constructor'],
616 dontEnumsLength = dontEnums.length;
617
618var argsTag = '[object Arguments]',
619 arrayTag = '[object Array]',
620 boolTag = '[object Boolean]',
621 dateTag = '[object Date]',
622 errorTag = '[object Error]',
623 funcTag = '[object Function]',
624 mapTag = '[object Map]',
625 numberTag = '[object Number]',
626 objectTag = '[object Object]',
627 regexpTag = '[object RegExp]',
628 setTag = '[object Set]',
629 stringTag = '[object String]',
630 weakMapTag = '[object WeakMap]';
631
632var arrayBufferTag = '[object ArrayBuffer]',
633 float32Tag = '[object Float32Array]',
634 float64Tag = '[object Float64Array]',
635 int8Tag = '[object Int8Array]',
636 int16Tag = '[object Int16Array]',
637 int32Tag = '[object Int32Array]',
638 uint8Tag = '[object Uint8Array]',
639 uint8ClampedTag = '[object Uint8ClampedArray]',
640 uint16Tag = '[object Uint16Array]',
641 uint32Tag = '[object Uint32Array]';
642
643var typedArrayTags = {};
644typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
645typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
646typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
647typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
648typedArrayTags[uint32Tag] = true;
649typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
650typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
651typedArrayTags[dateTag] = typedArrayTags[errorTag] =
652typedArrayTags[funcTag] = typedArrayTags[mapTag] =
653typedArrayTags[numberTag] = typedArrayTags[objectTag] =
654typedArrayTags[regexpTag] = typedArrayTags[setTag] =
655typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
656
657var objectProto = Object.prototype,
658 hasOwnProperty = objectProto.hasOwnProperty,
659 objToString = objectProto.toString,
660 MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
661
662var keys = Object.keys || (function() {
663 var hasOwnProperty = Object.prototype.hasOwnProperty,
664 hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
665 dontEnums = [
666 'toString',
667 'toLocaleString',
668 'valueOf',
669 'hasOwnProperty',
670 'isPrototypeOf',
671 'propertyIsEnumerable',
672 'constructor'
673 ],
674 dontEnumsLength = dontEnums.length;
675
676 return function(obj) {
677 if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
678 throw new TypeError('Object.keys called on non-object');
679 }
680
681 var result = [], prop, i;
682
683 for (prop in obj) {
684 if (hasOwnProperty.call(obj, prop)) {
685 result.push(prop);
686 }
687 }
688
689 if (hasDontEnumBug) {
690 for (i = 0; i < dontEnumsLength; i++) {
691 if (hasOwnProperty.call(obj, dontEnums[i])) {
692 result.push(dontEnums[i]);
693 }
694 }
695 }
696 return result;
697 };
698 }());
699
700function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
701 var objProps = keys(object),
702 objLength = objProps.length,
703 othProps = keys(other),
704 othLength = othProps.length;
705
706 if (objLength !== othLength && !isLoose) {
707 return false;
708 }
709 var index = objLength, key;
710 while (index--) {
711 key = objProps[index];
712 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
713 return false;
714 }
715 }
716 var skipCtor = isLoose;
717 while (++index < objLength) {
718 key = objProps[index];
719 var objValue = object[key],
720 othValue = other[key],
721 result;
722
723 if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
724 return false;
725 }
726 skipCtor || (skipCtor = key === 'constructor');
727 }
728 if (!skipCtor) {
729 var objCtor = object.constructor,
730 othCtor = other.constructor;
731
732 if (objCtor !== othCtor &&
733 ('constructor' in object && 'constructor' in other) &&
734 !(typeof objCtor === 'function' && objCtor instanceof objCtor &&
735 typeof othCtor === 'function' && othCtor instanceof othCtor)) {
736 return false;
737 }
738 }
739 return true;
740}
741
742function equalByTag(object, other, tag) {
743 switch (tag) {
744 case boolTag:
745 case dateTag:
746 return +object === +other;
747
748 case errorTag:
749 return object.name === other.name && object.message === other.message;
750
751 case numberTag:
752 return (object !== +object) ?
753 other !== +other :
754 object === +other;
755
756 case regexpTag:
757 case stringTag:
758 return object === (other + '');
759 }
760 return false;
761}
762
763var isObject = Rx.internals.isObject = function(value) {
764 var type = typeof value;
765 return !!value && (type === 'object' || type === 'function');
766};
767
768function isObjectLike(value) {
769 return !!value && typeof value === 'object';
770}
771
772function isLength(value) {
773 return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
774}
775
776var isHostObject = (function() {
777 try {
778 Object({ 'toString': 0 } + '');
779 } catch(e) {
780 return function() { return false; };
781 }
782 return function(value) {
783 return typeof value.toString !== 'function' && typeof (value + '') === 'string';
784 };
785}());
786
787function isTypedArray(value) {
788 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
789}
790
791var isArray = Array.isArray || function(value) {
792 return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
793};
794
795function arraySome (array, predicate) {
796 var index = -1,
797 length = array.length;
798
799 while (++index < length) {
800 if (predicate(array[index], index, array)) {
801 return true;
802 }
803 }
804 return false;
805}
806
807function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
808 var index = -1,
809 arrLength = array.length,
810 othLength = other.length;
811
812 if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
813 return false;
814 }
815 // Ignore non-index properties.
816 while (++index < arrLength) {
817 var arrValue = array[index],
818 othValue = other[index],
819 result;
820
821 if (result !== undefined) {
822 if (result) {
823 continue;
824 }
825 return false;
826 }
827 // Recursively compare arrays (susceptible to call stack limits).
828 if (isLoose) {
829 if (!arraySome(other, function(othValue) {
830 return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
831 })) {
832 return false;
833 }
834 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
835 return false;
836 }
837 }
838 return true;
839}
840
841function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
842 var objIsArr = isArray(object),
843 othIsArr = isArray(other),
844 objTag = arrayTag,
845 othTag = arrayTag;
846
847 if (!objIsArr) {
848 objTag = objToString.call(object);
849 if (objTag === argsTag) {
850 objTag = objectTag;
851 } else if (objTag !== objectTag) {
852 objIsArr = isTypedArray(object);
853 }
854 }
855 if (!othIsArr) {
856 othTag = objToString.call(other);
857 if (othTag === argsTag) {
858 othTag = objectTag;
859 }
860 }
861 var objIsObj = objTag === objectTag && !isHostObject(object),
862 othIsObj = othTag === objectTag && !isHostObject(other),
863 isSameTag = objTag === othTag;
864
865 if (isSameTag && !(objIsArr || objIsObj)) {
866 return equalByTag(object, other, objTag);
867 }
868 if (!isLoose) {
869 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
870 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
871
872 if (objIsWrapped || othIsWrapped) {
873 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
874 }
875 }
876 if (!isSameTag) {
877 return false;
878 }
879 // Assume cyclic values are equal.
880 // For more information on detecting circular references see https://es5.github.io/#JO.
881 stackA || (stackA = []);
882 stackB || (stackB = []);
883
884 var length = stackA.length;
885 while (length--) {
886 if (stackA[length] === object) {
887 return stackB[length] === other;
888 }
889 }
890 // Add `object` and `other` to the stack of traversed objects.
891 stackA.push(object);
892 stackB.push(other);
893
894 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
895
896 stackA.pop();
897 stackB.pop();
898
899 return result;
900}
901
902function baseIsEqual(value, other, isLoose, stackA, stackB) {
903 if (value === other) {
904 return true;
905 }
906 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
907 return value !== value && other !== other;
908 }
909 return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
910}
911
912var isEqual = Rx.internals.isEqual = function (value, other) {
913 return baseIsEqual(value, other);
914};
915
916 var hasProp = {}.hasOwnProperty,
917 slice = Array.prototype.slice;
918
919 var inherits = Rx.internals.inherits = function (child, parent) {
920 function __() { this.constructor = child; }
921 __.prototype = parent.prototype;
922 child.prototype = new __();
923 };
924
925 var addProperties = Rx.internals.addProperties = function (obj) {
926 for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
927 for (var idx = 0, ln = sources.length; idx < ln; idx++) {
928 var source = sources[idx];
929 for (var prop in source) {
930 obj[prop] = source[prop];
931 }
932 }
933 };
934
935 // Rx Utils
936 var addRef = Rx.internals.addRef = function (xs, r) {
937 return new AnonymousObservable(function (observer) {
938 return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));
939 });
940 };
941
942 function arrayInitialize(count, factory) {
943 var a = new Array(count);
944 for (var i = 0; i < count; i++) {
945 a[i] = factory();
946 }
947 return a;
948 }
949
950 function IndexedItem(id, value) {
951 this.id = id;
952 this.value = value;
953 }
954
955 IndexedItem.prototype.compareTo = function (other) {
956 var c = this.value.compareTo(other.value);
957 c === 0 && (c = this.id - other.id);
958 return c;
959 };
960
961 var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
962 this.items = new Array(capacity);
963 this.length = 0;
964 };
965
966 var priorityProto = PriorityQueue.prototype;
967 priorityProto.isHigherPriority = function (left, right) {
968 return this.items[left].compareTo(this.items[right]) < 0;
969 };
970
971 priorityProto.percolate = function (index) {
972 if (index >= this.length || index < 0) { return; }
973 var parent = index - 1 >> 1;
974 if (parent < 0 || parent === index) { return; }
975 if (this.isHigherPriority(index, parent)) {
976 var temp = this.items[index];
977 this.items[index] = this.items[parent];
978 this.items[parent] = temp;
979 this.percolate(parent);
980 }
981 };
982
983 priorityProto.heapify = function (index) {
984 +index || (index = 0);
985 if (index >= this.length || index < 0) { return; }
986 var left = 2 * index + 1,
987 right = 2 * index + 2,
988 first = index;
989 if (left < this.length && this.isHigherPriority(left, first)) {
990 first = left;
991 }
992 if (right < this.length && this.isHigherPriority(right, first)) {
993 first = right;
994 }
995 if (first !== index) {
996 var temp = this.items[index];
997 this.items[index] = this.items[first];
998 this.items[first] = temp;
999 this.heapify(first);
1000 }
1001 };
1002
1003 priorityProto.peek = function () { return this.items[0].value; };
1004
1005 priorityProto.removeAt = function (index) {
1006 this.items[index] = this.items[--this.length];
1007 this.items[this.length] = undefined;
1008 this.heapify();
1009 };
1010
1011 priorityProto.dequeue = function () {
1012 var result = this.peek();
1013 this.removeAt(0);
1014 return result;
1015 };
1016
1017 priorityProto.enqueue = function (item) {
1018 var index = this.length++;
1019 this.items[index] = new IndexedItem(PriorityQueue.count++, item);
1020 this.percolate(index);
1021 };
1022
1023 priorityProto.remove = function (item) {
1024 for (var i = 0; i < this.length; i++) {
1025 if (this.items[i].value === item) {
1026 this.removeAt(i);
1027 return true;
1028 }
1029 }
1030 return false;
1031 };
1032 PriorityQueue.count = 0;
1033
1034 /**
1035 * Represents a group of disposable resources that are disposed together.
1036 * @constructor
1037 */
1038 var CompositeDisposable = Rx.CompositeDisposable = function () {
1039 var args = [], i, len;
1040 if (Array.isArray(arguments[0])) {
1041 args = arguments[0];
1042 } else {
1043 len = arguments.length;
1044 args = new Array(len);
1045 for(i = 0; i < len; i++) { args[i] = arguments[i]; }
1046 }
1047 this.disposables = args;
1048 this.isDisposed = false;
1049 this.length = args.length;
1050 };
1051
1052 var CompositeDisposablePrototype = CompositeDisposable.prototype;
1053
1054 /**
1055 * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
1056 * @param {Mixed} item Disposable to add.
1057 */
1058 CompositeDisposablePrototype.add = function (item) {
1059 if (this.isDisposed) {
1060 item.dispose();
1061 } else {
1062 this.disposables.push(item);
1063 this.length++;
1064 }
1065 };
1066
1067 /**
1068 * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
1069 * @param {Mixed} item Disposable to remove.
1070 * @returns {Boolean} true if found; false otherwise.
1071 */
1072 CompositeDisposablePrototype.remove = function (item) {
1073 var shouldDispose = false;
1074 if (!this.isDisposed) {
1075 var idx = this.disposables.indexOf(item);
1076 if (idx !== -1) {
1077 shouldDispose = true;
1078 this.disposables.splice(idx, 1);
1079 this.length--;
1080 item.dispose();
1081 }
1082 }
1083 return shouldDispose;
1084 };
1085
1086 /**
1087 * Disposes all disposables in the group and removes them from the group.
1088 */
1089 CompositeDisposablePrototype.dispose = function () {
1090 if (!this.isDisposed) {
1091 this.isDisposed = true;
1092 var len = this.disposables.length, currentDisposables = new Array(len);
1093 for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
1094 this.disposables = [];
1095 this.length = 0;
1096
1097 for (i = 0; i < len; i++) {
1098 currentDisposables[i].dispose();
1099 }
1100 }
1101 };
1102
1103 /**
1104 * Provides a set of static methods for creating Disposables.
1105 * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
1106 */
1107 var Disposable = Rx.Disposable = function (action) {
1108 this.isDisposed = false;
1109 this.action = action || noop;
1110 };
1111
1112 /** Performs the task of cleaning up resources. */
1113 Disposable.prototype.dispose = function () {
1114 if (!this.isDisposed) {
1115 this.action();
1116 this.isDisposed = true;
1117 }
1118 };
1119
1120 /**
1121 * Creates a disposable object that invokes the specified action when disposed.
1122 * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
1123 * @return {Disposable} The disposable object that runs the given action upon disposal.
1124 */
1125 var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
1126
1127 /**
1128 * Gets the disposable that does nothing when disposed.
1129 */
1130 var disposableEmpty = Disposable.empty = { dispose: noop };
1131
1132 /**
1133 * Validates whether the given object is a disposable
1134 * @param {Object} Object to test whether it has a dispose method
1135 * @returns {Boolean} true if a disposable object, else false.
1136 */
1137 var isDisposable = Disposable.isDisposable = function (d) {
1138 return d && isFunction(d.dispose);
1139 };
1140
1141 var checkDisposed = Disposable.checkDisposed = function (disposable) {
1142 if (disposable.isDisposed) { throw new ObjectDisposedError(); }
1143 };
1144
1145 var disposableFixup = Disposable._fixup = function (result) {
1146 return isDisposable(result) ? result : disposableEmpty;
1147 };
1148
1149 // Single assignment
1150 var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
1151 this.isDisposed = false;
1152 this.current = null;
1153 };
1154 SingleAssignmentDisposable.prototype.getDisposable = function () {
1155 return this.current;
1156 };
1157 SingleAssignmentDisposable.prototype.setDisposable = function (value) {
1158 if (this.current) { throw new Error('Disposable has already been assigned'); }
1159 var shouldDispose = this.isDisposed;
1160 !shouldDispose && (this.current = value);
1161 shouldDispose && value && value.dispose();
1162 };
1163 SingleAssignmentDisposable.prototype.dispose = function () {
1164 if (!this.isDisposed) {
1165 this.isDisposed = true;
1166 var old = this.current;
1167 this.current = null;
1168 old && old.dispose();
1169 }
1170 };
1171
1172 // Multiple assignment disposable
1173 var SerialDisposable = Rx.SerialDisposable = function () {
1174 this.isDisposed = false;
1175 this.current = null;
1176 };
1177 SerialDisposable.prototype.getDisposable = function () {
1178 return this.current;
1179 };
1180 SerialDisposable.prototype.setDisposable = function (value) {
1181 var shouldDispose = this.isDisposed;
1182 if (!shouldDispose) {
1183 var old = this.current;
1184 this.current = value;
1185 }
1186 old && old.dispose();
1187 shouldDispose && value && value.dispose();
1188 };
1189 SerialDisposable.prototype.dispose = function () {
1190 if (!this.isDisposed) {
1191 this.isDisposed = true;
1192 var old = this.current;
1193 this.current = null;
1194 }
1195 old && old.dispose();
1196 };
1197
1198 var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {
1199 this._first = first;
1200 this._second = second;
1201 this.isDisposed = false;
1202 };
1203
1204 BinaryDisposable.prototype.dispose = function () {
1205 if (!this.isDisposed) {
1206 this.isDisposed = true;
1207 var old1 = this._first;
1208 this._first = null;
1209 old1 && old1.dispose();
1210 var old2 = this._second;
1211 this._second = null;
1212 old2 && old2.dispose();
1213 }
1214 };
1215
1216 var NAryDisposable = Rx.NAryDisposable = function (disposables) {
1217 this._disposables = disposables;
1218 this.isDisposed = false;
1219 };
1220
1221 NAryDisposable.prototype.dispose = function () {
1222 if (!this.isDisposed) {
1223 this.isDisposed = true;
1224 for (var i = 0, len = this._disposables.length; i < len; i++) {
1225 this._disposables[i].dispose();
1226 }
1227 this._disposables.length = 0;
1228 }
1229 };
1230
1231 /**
1232 * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
1233 */
1234 var RefCountDisposable = Rx.RefCountDisposable = (function () {
1235
1236 function InnerDisposable(disposable) {
1237 this.disposable = disposable;
1238 this.disposable.count++;
1239 this.isInnerDisposed = false;
1240 }
1241
1242 InnerDisposable.prototype.dispose = function () {
1243 if (!this.disposable.isDisposed && !this.isInnerDisposed) {
1244 this.isInnerDisposed = true;
1245 this.disposable.count--;
1246 if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
1247 this.disposable.isDisposed = true;
1248 this.disposable.underlyingDisposable.dispose();
1249 }
1250 }
1251 };
1252
1253 /**
1254 * Initializes a new instance of the RefCountDisposable with the specified disposable.
1255 * @constructor
1256 * @param {Disposable} disposable Underlying disposable.
1257 */
1258 function RefCountDisposable(disposable) {
1259 this.underlyingDisposable = disposable;
1260 this.isDisposed = false;
1261 this.isPrimaryDisposed = false;
1262 this.count = 0;
1263 }
1264
1265 /**
1266 * Disposes the underlying disposable only when all dependent disposables have been disposed
1267 */
1268 RefCountDisposable.prototype.dispose = function () {
1269 if (!this.isDisposed && !this.isPrimaryDisposed) {
1270 this.isPrimaryDisposed = true;
1271 if (this.count === 0) {
1272 this.isDisposed = true;
1273 this.underlyingDisposable.dispose();
1274 }
1275 }
1276 };
1277
1278 /**
1279 * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
1280 * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
1281 */
1282 RefCountDisposable.prototype.getDisposable = function () {
1283 return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
1284 };
1285
1286 return RefCountDisposable;
1287 })();
1288
1289 function ScheduledDisposable(scheduler, disposable) {
1290 this.scheduler = scheduler;
1291 this.disposable = disposable;
1292 this.isDisposed = false;
1293 }
1294
1295 function scheduleItem(s, self) {
1296 if (!self.isDisposed) {
1297 self.isDisposed = true;
1298 self.disposable.dispose();
1299 }
1300 }
1301
1302 ScheduledDisposable.prototype.dispose = function () {
1303 this.scheduler.schedule(this, scheduleItem);
1304 };
1305
1306 var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
1307 this.scheduler = scheduler;
1308 this.state = state;
1309 this.action = action;
1310 this.dueTime = dueTime;
1311 this.comparer = comparer || defaultSubComparer;
1312 this.disposable = new SingleAssignmentDisposable();
1313 };
1314
1315 ScheduledItem.prototype.invoke = function () {
1316 this.disposable.setDisposable(this.invokeCore());
1317 };
1318
1319 ScheduledItem.prototype.compareTo = function (other) {
1320 return this.comparer(this.dueTime, other.dueTime);
1321 };
1322
1323 ScheduledItem.prototype.isCancelled = function () {
1324 return this.disposable.isDisposed;
1325 };
1326
1327 ScheduledItem.prototype.invokeCore = function () {
1328 return disposableFixup(this.action(this.scheduler, this.state));
1329 };
1330
1331 /** Provides a set of static properties to access commonly used schedulers. */
1332 var Scheduler = Rx.Scheduler = (function () {
1333
1334 function Scheduler() { }
1335
1336 /** Determines whether the given object is a scheduler */
1337 Scheduler.isScheduler = function (s) {
1338 return s instanceof Scheduler;
1339 };
1340
1341 var schedulerProto = Scheduler.prototype;
1342
1343 /**
1344 * Schedules an action to be executed.
1345 * @param state State passed to the action to be executed.
1346 * @param {Function} action Action to be executed.
1347 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1348 */
1349 schedulerProto.schedule = function (state, action) {
1350 throw new NotImplementedError();
1351 };
1352
1353 /**
1354 * Schedules an action to be executed after dueTime.
1355 * @param state State passed to the action to be executed.
1356 * @param {Function} action Action to be executed.
1357 * @param {Number} dueTime Relative time after which to execute the action.
1358 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1359 */
1360 schedulerProto.scheduleFuture = function (state, dueTime, action) {
1361 var dt = dueTime;
1362 dt instanceof Date && (dt = dt - this.now());
1363 dt = Scheduler.normalize(dt);
1364
1365 if (dt === 0) { return this.schedule(state, action); }
1366
1367 return this._scheduleFuture(state, dt, action);
1368 };
1369
1370 schedulerProto._scheduleFuture = function (state, dueTime, action) {
1371 throw new NotImplementedError();
1372 };
1373
1374 /** Gets the current time according to the local machine's system clock. */
1375 Scheduler.now = defaultNow;
1376
1377 /** Gets the current time according to the local machine's system clock. */
1378 Scheduler.prototype.now = defaultNow;
1379
1380 /**
1381 * Normalizes the specified TimeSpan value to a positive value.
1382 * @param {Number} timeSpan The time span value to normalize.
1383 * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
1384 */
1385 Scheduler.normalize = function (timeSpan) {
1386 timeSpan < 0 && (timeSpan = 0);
1387 return timeSpan;
1388 };
1389
1390 return Scheduler;
1391 }());
1392
1393 var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
1394
1395 (function (schedulerProto) {
1396
1397 function invokeRecImmediate(scheduler, pair) {
1398 var state = pair[0], action = pair[1], group = new CompositeDisposable();
1399 action(state, innerAction);
1400 return group;
1401
1402 function innerAction(state2) {
1403 var isAdded = false, isDone = false;
1404
1405 var d = scheduler.schedule(state2, scheduleWork);
1406 if (!isDone) {
1407 group.add(d);
1408 isAdded = true;
1409 }
1410
1411 function scheduleWork(_, state3) {
1412 if (isAdded) {
1413 group.remove(d);
1414 } else {
1415 isDone = true;
1416 }
1417 action(state3, innerAction);
1418 return disposableEmpty;
1419 }
1420 }
1421 }
1422
1423 function invokeRecDate(scheduler, pair) {
1424 var state = pair[0], action = pair[1], group = new CompositeDisposable();
1425 action(state, innerAction);
1426 return group;
1427
1428 function innerAction(state2, dueTime1) {
1429 var isAdded = false, isDone = false;
1430
1431 var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);
1432 if (!isDone) {
1433 group.add(d);
1434 isAdded = true;
1435 }
1436
1437 function scheduleWork(_, state3) {
1438 if (isAdded) {
1439 group.remove(d);
1440 } else {
1441 isDone = true;
1442 }
1443 action(state3, innerAction);
1444 return disposableEmpty;
1445 }
1446 }
1447 }
1448
1449 /**
1450 * Schedules an action to be executed recursively.
1451 * @param {Mixed} state State passed to the action to be executed.
1452 * @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.
1453 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1454 */
1455 schedulerProto.scheduleRecursive = function (state, action) {
1456 return this.schedule([state, action], invokeRecImmediate);
1457 };
1458
1459 /**
1460 * Schedules an action to be executed recursively after a specified relative or absolute due time.
1461 * @param {Mixed} state State passed to the action to be executed.
1462 * @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.
1463 * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.
1464 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1465 */
1466 schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {
1467 return this.scheduleFuture([state, action], dueTime, invokeRecDate);
1468 };
1469
1470 }(Scheduler.prototype));
1471
1472 (function (schedulerProto) {
1473
1474 /**
1475 * 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.
1476 * @param {Mixed} state Initial state passed to the action upon the first iteration.
1477 * @param {Number} period Period for running the work periodically.
1478 * @param {Function} action Action to be executed, potentially updating the state.
1479 * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
1480 */
1481 schedulerProto.schedulePeriodic = function(state, period, action) {
1482 if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
1483 period = normalizeTime(period);
1484 var s = state, id = root.setInterval(function () { s = action(s); }, period);
1485 return disposableCreate(function () { root.clearInterval(id); });
1486 };
1487
1488 }(Scheduler.prototype));
1489
1490 (function (schedulerProto) {
1491 /**
1492 * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
1493 * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
1494 * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
1495 */
1496 schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
1497 return new CatchScheduler(this, handler);
1498 };
1499 }(Scheduler.prototype));
1500
1501 var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
1502 function createTick(self) {
1503 return function tick(command, recurse) {
1504 recurse(0, self._period);
1505 var state = tryCatch(self._action)(self._state);
1506 if (state === errorObj) {
1507 self._cancel.dispose();
1508 thrower(state.e);
1509 }
1510 self._state = state;
1511 };
1512 }
1513
1514 function SchedulePeriodicRecursive(scheduler, state, period, action) {
1515 this._scheduler = scheduler;
1516 this._state = state;
1517 this._period = period;
1518 this._action = action;
1519 }
1520
1521 SchedulePeriodicRecursive.prototype.start = function () {
1522 var d = new SingleAssignmentDisposable();
1523 this._cancel = d;
1524 d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
1525
1526 return d;
1527 };
1528
1529 return SchedulePeriodicRecursive;
1530 }());
1531
1532 /** Gets a scheduler that schedules work immediately on the current thread. */
1533 var ImmediateScheduler = (function (__super__) {
1534 inherits(ImmediateScheduler, __super__);
1535 function ImmediateScheduler() {
1536 __super__.call(this);
1537 }
1538
1539 ImmediateScheduler.prototype.schedule = function (state, action) {
1540 return disposableFixup(action(this, state));
1541 };
1542
1543 return ImmediateScheduler;
1544 }(Scheduler));
1545
1546 var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();
1547
1548 /**
1549 * Gets a scheduler that schedules work as soon as possible on the current thread.
1550 */
1551 var CurrentThreadScheduler = (function (__super__) {
1552 var queue;
1553
1554 function runTrampoline () {
1555 while (queue.length > 0) {
1556 var item = queue.dequeue();
1557 !item.isCancelled() && item.invoke();
1558 }
1559 }
1560
1561 inherits(CurrentThreadScheduler, __super__);
1562 function CurrentThreadScheduler() {
1563 __super__.call(this);
1564 }
1565
1566 CurrentThreadScheduler.prototype.schedule = function (state, action) {
1567 var si = new ScheduledItem(this, state, action, this.now());
1568
1569 if (!queue) {
1570 queue = new PriorityQueue(4);
1571 queue.enqueue(si);
1572
1573 var result = tryCatch(runTrampoline)();
1574 queue = null;
1575 if (result === errorObj) { thrower(result.e); }
1576 } else {
1577 queue.enqueue(si);
1578 }
1579 return si.disposable;
1580 };
1581
1582 CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };
1583
1584 return CurrentThreadScheduler;
1585 }(Scheduler));
1586
1587 var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();
1588
1589 var scheduleMethod, clearMethod;
1590
1591 var localTimer = (function () {
1592 var localSetTimeout, localClearTimeout = noop;
1593 if (!!root.setTimeout) {
1594 localSetTimeout = root.setTimeout;
1595 localClearTimeout = root.clearTimeout;
1596 } else if (!!root.WScript) {
1597 localSetTimeout = function (fn, time) {
1598 root.WScript.Sleep(time);
1599 fn();
1600 };
1601 } else {
1602 throw new NotSupportedError();
1603 }
1604
1605 return {
1606 setTimeout: localSetTimeout,
1607 clearTimeout: localClearTimeout
1608 };
1609 }());
1610 var localSetTimeout = localTimer.setTimeout,
1611 localClearTimeout = localTimer.clearTimeout;
1612
1613 (function () {
1614
1615 var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
1616
1617 clearMethod = function (handle) {
1618 delete tasksByHandle[handle];
1619 };
1620
1621 function runTask(handle) {
1622 if (currentlyRunning) {
1623 localSetTimeout(function () { runTask(handle); }, 0);
1624 } else {
1625 var task = tasksByHandle[handle];
1626 if (task) {
1627 currentlyRunning = true;
1628 var result = tryCatch(task)();
1629 clearMethod(handle);
1630 currentlyRunning = false;
1631 if (result === errorObj) { thrower(result.e); }
1632 }
1633 }
1634 }
1635
1636 var reNative = new RegExp('^' +
1637 String(toString)
1638 .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1639 .replace(/toString| for [^\]]+/g, '.*?') + '$'
1640 );
1641
1642 var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
1643 !reNative.test(setImmediate) && setImmediate;
1644
1645 function postMessageSupported () {
1646 // Ensure not in a worker
1647 if (!root.postMessage || root.importScripts) { return false; }
1648 var isAsync = false, oldHandler = root.onmessage;
1649 // Test for async
1650 root.onmessage = function () { isAsync = true; };
1651 root.postMessage('', '*');
1652 root.onmessage = oldHandler;
1653
1654 return isAsync;
1655 }
1656
1657 // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
1658 if (isFunction(setImmediate)) {
1659 scheduleMethod = function (action) {
1660 var id = nextHandle++;
1661 tasksByHandle[id] = action;
1662 setImmediate(function () { runTask(id); });
1663
1664 return id;
1665 };
1666 } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
1667 scheduleMethod = function (action) {
1668 var id = nextHandle++;
1669 tasksByHandle[id] = action;
1670 process.nextTick(function () { runTask(id); });
1671
1672 return id;
1673 };
1674 } else if (postMessageSupported()) {
1675 var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
1676
1677 var onGlobalPostMessage = function (event) {
1678 // Only if we're a match to avoid any other global events
1679 if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
1680 runTask(event.data.substring(MSG_PREFIX.length));
1681 }
1682 };
1683
1684 root.addEventListener('message', onGlobalPostMessage, false);
1685
1686 scheduleMethod = function (action) {
1687 var id = nextHandle++;
1688 tasksByHandle[id] = action;
1689 root.postMessage(MSG_PREFIX + currentId, '*');
1690 return id;
1691 };
1692 } else if (!!root.MessageChannel) {
1693 var channel = new root.MessageChannel();
1694
1695 channel.port1.onmessage = function (e) { runTask(e.data); };
1696
1697 scheduleMethod = function (action) {
1698 var id = nextHandle++;
1699 tasksByHandle[id] = action;
1700 channel.port2.postMessage(id);
1701 return id;
1702 };
1703 } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
1704
1705 scheduleMethod = function (action) {
1706 var scriptElement = root.document.createElement('script');
1707 var id = nextHandle++;
1708 tasksByHandle[id] = action;
1709
1710 scriptElement.onreadystatechange = function () {
1711 runTask(id);
1712 scriptElement.onreadystatechange = null;
1713 scriptElement.parentNode.removeChild(scriptElement);
1714 scriptElement = null;
1715 };
1716 root.document.documentElement.appendChild(scriptElement);
1717 return id;
1718 };
1719
1720 } else {
1721 scheduleMethod = function (action) {
1722 var id = nextHandle++;
1723 tasksByHandle[id] = action;
1724 localSetTimeout(function () {
1725 runTask(id);
1726 }, 0);
1727
1728 return id;
1729 };
1730 }
1731 }());
1732
1733 /**
1734 * Gets a scheduler that schedules work via a timed callback based upon platform.
1735 */
1736 var DefaultScheduler = (function (__super__) {
1737 inherits(DefaultScheduler, __super__);
1738 function DefaultScheduler() {
1739 __super__.call(this);
1740 }
1741
1742 function scheduleAction(disposable, action, scheduler, state) {
1743 return function schedule() {
1744 disposable.setDisposable(Disposable._fixup(action(scheduler, state)));
1745 };
1746 }
1747
1748 function ClearDisposable(id) {
1749 this._id = id;
1750 this.isDisposed = false;
1751 }
1752
1753 ClearDisposable.prototype.dispose = function () {
1754 if (!this.isDisposed) {
1755 this.isDisposed = true;
1756 clearMethod(this._id);
1757 }
1758 };
1759
1760 function LocalClearDisposable(id) {
1761 this._id = id;
1762 this.isDisposed = false;
1763 }
1764
1765 LocalClearDisposable.prototype.dispose = function () {
1766 if (!this.isDisposed) {
1767 this.isDisposed = true;
1768 localClearTimeout(this._id);
1769 }
1770 };
1771
1772 DefaultScheduler.prototype.schedule = function (state, action) {
1773 var disposable = new SingleAssignmentDisposable(),
1774 id = scheduleMethod(scheduleAction(disposable, action, this, state));
1775 return new BinaryDisposable(disposable, new ClearDisposable(id));
1776 };
1777
1778 DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
1779 if (dueTime === 0) { return this.schedule(state, action); }
1780 var disposable = new SingleAssignmentDisposable(),
1781 id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);
1782 return new BinaryDisposable(disposable, new LocalClearDisposable(id));
1783 };
1784
1785 return DefaultScheduler;
1786 }(Scheduler));
1787
1788 var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();
1789
1790 var CatchScheduler = (function (__super__) {
1791 inherits(CatchScheduler, __super__);
1792
1793 function CatchScheduler(scheduler, handler) {
1794 this._scheduler = scheduler;
1795 this._handler = handler;
1796 this._recursiveOriginal = null;
1797 this._recursiveWrapper = null;
1798 __super__.call(this);
1799 }
1800
1801 CatchScheduler.prototype.schedule = function (state, action) {
1802 return this._scheduler.schedule(state, this._wrap(action));
1803 };
1804
1805 CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
1806 return this._scheduler.schedule(state, dueTime, this._wrap(action));
1807 };
1808
1809 CatchScheduler.prototype.now = function () { return this._scheduler.now(); };
1810
1811 CatchScheduler.prototype._clone = function (scheduler) {
1812 return new CatchScheduler(scheduler, this._handler);
1813 };
1814
1815 CatchScheduler.prototype._wrap = function (action) {
1816 var parent = this;
1817 return function (self, state) {
1818 var res = tryCatch(action)(parent._getRecursiveWrapper(self), state);
1819 if (res === errorObj) {
1820 if (!parent._handler(res.e)) { thrower(res.e); }
1821 return disposableEmpty;
1822 }
1823 return disposableFixup(res);
1824 };
1825 };
1826
1827 CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
1828 if (this._recursiveOriginal !== scheduler) {
1829 this._recursiveOriginal = scheduler;
1830 var wrapper = this._clone(scheduler);
1831 wrapper._recursiveOriginal = scheduler;
1832 wrapper._recursiveWrapper = wrapper;
1833 this._recursiveWrapper = wrapper;
1834 }
1835 return this._recursiveWrapper;
1836 };
1837
1838 CatchScheduler.prototype.schedulePeriodic = function (state, period, action) {
1839 var self = this, failed = false, d = new SingleAssignmentDisposable();
1840
1841 d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) {
1842 if (failed) { return null; }
1843 var res = tryCatch(action)(state1);
1844 if (res === errorObj) {
1845 failed = true;
1846 if (!self._handler(res.e)) { thrower(res.e); }
1847 d.dispose();
1848 return null;
1849 }
1850 return res;
1851 }));
1852
1853 return d;
1854 };
1855
1856 return CatchScheduler;
1857 }(Scheduler));
1858
1859 /**
1860 * Represents a notification to an observer.
1861 */
1862 var Notification = Rx.Notification = (function () {
1863 function Notification() {
1864
1865 }
1866
1867 Notification.prototype._accept = function (onNext, onError, onCompleted) {
1868 throw new NotImplementedError();
1869 };
1870
1871 Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
1872 throw new NotImplementedError();
1873 };
1874
1875 /**
1876 * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
1877 * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
1878 * @param {Function} onError Function to invoke for an OnError notification.
1879 * @param {Function} onCompleted Function to invoke for an OnCompleted notification.
1880 * @returns {Any} Result produced by the observation.
1881 */
1882 Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
1883 return observerOrOnNext && typeof observerOrOnNext === 'object' ?
1884 this._acceptObserver(observerOrOnNext) :
1885 this._accept(observerOrOnNext, onError, onCompleted);
1886 };
1887
1888 /**
1889 * Returns an observable sequence with a single notification.
1890 *
1891 * @memberOf Notifications
1892 * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
1893 * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
1894 */
1895 Notification.prototype.toObservable = function (scheduler) {
1896 var self = this;
1897 isScheduler(scheduler) || (scheduler = immediateScheduler);
1898 return new AnonymousObservable(function (o) {
1899 return scheduler.schedule(self, function (_, notification) {
1900 notification._acceptObserver(o);
1901 notification.kind === 'N' && o.onCompleted();
1902 });
1903 });
1904 };
1905
1906 return Notification;
1907 })();
1908
1909 var OnNextNotification = (function (__super__) {
1910 inherits(OnNextNotification, __super__);
1911 function OnNextNotification(value) {
1912 this.value = value;
1913 this.kind = 'N';
1914 }
1915
1916 OnNextNotification.prototype._accept = function (onNext) {
1917 return onNext(this.value);
1918 };
1919
1920 OnNextNotification.prototype._acceptObserver = function (o) {
1921 return o.onNext(this.value);
1922 };
1923
1924 OnNextNotification.prototype.toString = function () {
1925 return 'OnNext(' + this.value + ')';
1926 };
1927
1928 return OnNextNotification;
1929 }(Notification));
1930
1931 var OnErrorNotification = (function (__super__) {
1932 inherits(OnErrorNotification, __super__);
1933 function OnErrorNotification(error) {
1934 this.error = error;
1935 this.kind = 'E';
1936 }
1937
1938 OnErrorNotification.prototype._accept = function (onNext, onError) {
1939 return onError(this.error);
1940 };
1941
1942 OnErrorNotification.prototype._acceptObserver = function (o) {
1943 return o.onError(this.error);
1944 };
1945
1946 OnErrorNotification.prototype.toString = function () {
1947 return 'OnError(' + this.error + ')';
1948 };
1949
1950 return OnErrorNotification;
1951 }(Notification));
1952
1953 var OnCompletedNotification = (function (__super__) {
1954 inherits(OnCompletedNotification, __super__);
1955 function OnCompletedNotification() {
1956 this.kind = 'C';
1957 }
1958
1959 OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
1960 return onCompleted();
1961 };
1962
1963 OnCompletedNotification.prototype._acceptObserver = function (o) {
1964 return o.onCompleted();
1965 };
1966
1967 OnCompletedNotification.prototype.toString = function () {
1968 return 'OnCompleted()';
1969 };
1970
1971 return OnCompletedNotification;
1972 }(Notification));
1973
1974 /**
1975 * Creates an object that represents an OnNext notification to an observer.
1976 * @param {Any} value The value contained in the notification.
1977 * @returns {Notification} The OnNext notification containing the value.
1978 */
1979 var notificationCreateOnNext = Notification.createOnNext = function (value) {
1980 return new OnNextNotification(value);
1981 };
1982
1983 /**
1984 * Creates an object that represents an OnError notification to an observer.
1985 * @param {Any} error The exception contained in the notification.
1986 * @returns {Notification} The OnError notification containing the exception.
1987 */
1988 var notificationCreateOnError = Notification.createOnError = function (error) {
1989 return new OnErrorNotification(error);
1990 };
1991
1992 /**
1993 * Creates an object that represents an OnCompleted notification to an observer.
1994 * @returns {Notification} The OnCompleted notification.
1995 */
1996 var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
1997 return new OnCompletedNotification();
1998 };
1999
2000 /**
2001 * Supports push-style iteration over an observable sequence.
2002 */
2003 var Observer = Rx.Observer = function () { };
2004
2005 /**
2006 * Creates a notification callback from an observer.
2007 * @returns The action that forwards its input notification to the underlying observer.
2008 */
2009 Observer.prototype.toNotifier = function () {
2010 var observer = this;
2011 return function (n) { return n.accept(observer); };
2012 };
2013
2014 /**
2015 * Hides the identity of an observer.
2016 * @returns An observer that hides the identity of the specified observer.
2017 */
2018 Observer.prototype.asObserver = function () {
2019 var self = this;
2020 return new AnonymousObserver(
2021 function (x) { self.onNext(x); },
2022 function (err) { self.onError(err); },
2023 function () { self.onCompleted(); });
2024 };
2025
2026 /**
2027 * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
2028 * If a violation is detected, an Error is thrown from the offending observer method call.
2029 * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
2030 */
2031 Observer.prototype.checked = function () { return new CheckedObserver(this); };
2032
2033 /**
2034 * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
2035 * @param {Function} [onNext] Observer's OnNext action implementation.
2036 * @param {Function} [onError] Observer's OnError action implementation.
2037 * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
2038 * @returns {Observer} The observer object implemented using the given actions.
2039 */
2040 var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
2041 onNext || (onNext = noop);
2042 onError || (onError = defaultError);
2043 onCompleted || (onCompleted = noop);
2044 return new AnonymousObserver(onNext, onError, onCompleted);
2045 };
2046
2047 /**
2048 * Creates an observer from a notification callback.
2049 * @param {Function} handler Action that handles a notification.
2050 * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
2051 */
2052 Observer.fromNotifier = function (handler, thisArg) {
2053 var cb = bindCallback(handler, thisArg, 1);
2054 return new AnonymousObserver(function (x) {
2055 return cb(notificationCreateOnNext(x));
2056 }, function (e) {
2057 return cb(notificationCreateOnError(e));
2058 }, function () {
2059 return cb(notificationCreateOnCompleted());
2060 });
2061 };
2062
2063 /**
2064 * Schedules the invocation of observer methods on the given scheduler.
2065 * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
2066 * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
2067 */
2068 Observer.prototype.notifyOn = function (scheduler) {
2069 return new ObserveOnObserver(scheduler, this);
2070 };
2071
2072 Observer.prototype.makeSafe = function(disposable) {
2073 return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
2074 };
2075
2076 /**
2077 * Abstract base class for implementations of the Observer class.
2078 * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
2079 */
2080 var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
2081 inherits(AbstractObserver, __super__);
2082
2083 /**
2084 * Creates a new observer in a non-stopped state.
2085 */
2086 function AbstractObserver() {
2087 this.isStopped = false;
2088 }
2089
2090 // Must be implemented by other observers
2091 AbstractObserver.prototype.next = notImplemented;
2092 AbstractObserver.prototype.error = notImplemented;
2093 AbstractObserver.prototype.completed = notImplemented;
2094
2095 /**
2096 * Notifies the observer of a new element in the sequence.
2097 * @param {Any} value Next element in the sequence.
2098 */
2099 AbstractObserver.prototype.onNext = function (value) {
2100 !this.isStopped && this.next(value);
2101 };
2102
2103 /**
2104 * Notifies the observer that an exception has occurred.
2105 * @param {Any} error The error that has occurred.
2106 */
2107 AbstractObserver.prototype.onError = function (error) {
2108 if (!this.isStopped) {
2109 this.isStopped = true;
2110 this.error(error);
2111 }
2112 };
2113
2114 /**
2115 * Notifies the observer of the end of the sequence.
2116 */
2117 AbstractObserver.prototype.onCompleted = function () {
2118 if (!this.isStopped) {
2119 this.isStopped = true;
2120 this.completed();
2121 }
2122 };
2123
2124 /**
2125 * Disposes the observer, causing it to transition to the stopped state.
2126 */
2127 AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
2128
2129 AbstractObserver.prototype.fail = function (e) {
2130 if (!this.isStopped) {
2131 this.isStopped = true;
2132 this.error(e);
2133 return true;
2134 }
2135
2136 return false;
2137 };
2138
2139 return AbstractObserver;
2140 }(Observer));
2141
2142 /**
2143 * Class to create an Observer instance from delegate-based implementations of the on* methods.
2144 */
2145 var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
2146 inherits(AnonymousObserver, __super__);
2147
2148 /**
2149 * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
2150 * @param {Any} onNext Observer's OnNext action implementation.
2151 * @param {Any} onError Observer's OnError action implementation.
2152 * @param {Any} onCompleted Observer's OnCompleted action implementation.
2153 */
2154 function AnonymousObserver(onNext, onError, onCompleted) {
2155 __super__.call(this);
2156 this._onNext = onNext;
2157 this._onError = onError;
2158 this._onCompleted = onCompleted;
2159 }
2160
2161 /**
2162 * Calls the onNext action.
2163 * @param {Any} value Next element in the sequence.
2164 */
2165 AnonymousObserver.prototype.next = function (value) {
2166 this._onNext(value);
2167 };
2168
2169 /**
2170 * Calls the onError action.
2171 * @param {Any} error The error that has occurred.
2172 */
2173 AnonymousObserver.prototype.error = function (error) {
2174 this._onError(error);
2175 };
2176
2177 /**
2178 * Calls the onCompleted action.
2179 */
2180 AnonymousObserver.prototype.completed = function () {
2181 this._onCompleted();
2182 };
2183
2184 return AnonymousObserver;
2185 }(AbstractObserver));
2186
2187 var CheckedObserver = (function (__super__) {
2188 inherits(CheckedObserver, __super__);
2189
2190 function CheckedObserver(observer) {
2191 __super__.call(this);
2192 this._observer = observer;
2193 this._state = 0; // 0 - idle, 1 - busy, 2 - done
2194 }
2195
2196 var CheckedObserverPrototype = CheckedObserver.prototype;
2197
2198 CheckedObserverPrototype.onNext = function (value) {
2199 this.checkAccess();
2200 var res = tryCatch(this._observer.onNext).call(this._observer, value);
2201 this._state = 0;
2202 res === errorObj && thrower(res.e);
2203 };
2204
2205 CheckedObserverPrototype.onError = function (err) {
2206 this.checkAccess();
2207 var res = tryCatch(this._observer.onError).call(this._observer, err);
2208 this._state = 2;
2209 res === errorObj && thrower(res.e);
2210 };
2211
2212 CheckedObserverPrototype.onCompleted = function () {
2213 this.checkAccess();
2214 var res = tryCatch(this._observer.onCompleted).call(this._observer);
2215 this._state = 2;
2216 res === errorObj && thrower(res.e);
2217 };
2218
2219 CheckedObserverPrototype.checkAccess = function () {
2220 if (this._state === 1) { throw new Error('Re-entrancy detected'); }
2221 if (this._state === 2) { throw new Error('Observer completed'); }
2222 if (this._state === 0) { this._state = 1; }
2223 };
2224
2225 return CheckedObserver;
2226 }(Observer));
2227
2228 var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
2229 inherits(ScheduledObserver, __super__);
2230
2231 function ScheduledObserver(scheduler, observer) {
2232 __super__.call(this);
2233 this.scheduler = scheduler;
2234 this.observer = observer;
2235 this.isAcquired = false;
2236 this.hasFaulted = false;
2237 this.queue = [];
2238 this.disposable = new SerialDisposable();
2239 }
2240
2241 function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }
2242 function enqueueError(observer, e) { return function () { observer.onError(e); }; }
2243 function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }
2244
2245 ScheduledObserver.prototype.next = function (x) {
2246 this.queue.push(enqueueNext(this.observer, x));
2247 };
2248
2249 ScheduledObserver.prototype.error = function (e) {
2250 this.queue.push(enqueueError(this.observer, e));
2251 };
2252
2253 ScheduledObserver.prototype.completed = function () {
2254 this.queue.push(enqueueCompleted(this.observer));
2255 };
2256
2257
2258 function scheduleMethod(state, recurse) {
2259 var work;
2260 if (state.queue.length > 0) {
2261 work = state.queue.shift();
2262 } else {
2263 state.isAcquired = false;
2264 return;
2265 }
2266 var res = tryCatch(work)();
2267 if (res === errorObj) {
2268 state.queue = [];
2269 state.hasFaulted = true;
2270 return thrower(res.e);
2271 }
2272 recurse(state);
2273 }
2274
2275 ScheduledObserver.prototype.ensureActive = function () {
2276 var isOwner = false;
2277 if (!this.hasFaulted && this.queue.length > 0) {
2278 isOwner = !this.isAcquired;
2279 this.isAcquired = true;
2280 }
2281 isOwner &&
2282 this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));
2283 };
2284
2285 ScheduledObserver.prototype.dispose = function () {
2286 __super__.prototype.dispose.call(this);
2287 this.disposable.dispose();
2288 };
2289
2290 return ScheduledObserver;
2291 }(AbstractObserver));
2292
2293 var ObserveOnObserver = (function (__super__) {
2294 inherits(ObserveOnObserver, __super__);
2295
2296 function ObserveOnObserver(scheduler, observer, cancel) {
2297 __super__.call(this, scheduler, observer);
2298 this._cancel = cancel;
2299 }
2300
2301 ObserveOnObserver.prototype.next = function (value) {
2302 __super__.prototype.next.call(this, value);
2303 this.ensureActive();
2304 };
2305
2306 ObserveOnObserver.prototype.error = function (e) {
2307 __super__.prototype.error.call(this, e);
2308 this.ensureActive();
2309 };
2310
2311 ObserveOnObserver.prototype.completed = function () {
2312 __super__.prototype.completed.call(this);
2313 this.ensureActive();
2314 };
2315
2316 ObserveOnObserver.prototype.dispose = function () {
2317 __super__.prototype.dispose.call(this);
2318 this._cancel && this._cancel.dispose();
2319 this._cancel = null;
2320 };
2321
2322 return ObserveOnObserver;
2323 })(ScheduledObserver);
2324
2325 var observableProto;
2326
2327 /**
2328 * Represents a push-style collection.
2329 */
2330 var Observable = Rx.Observable = (function () {
2331
2332 function makeSubscribe(self, subscribe) {
2333 return function (o) {
2334 var oldOnError = o.onError;
2335 o.onError = function (e) {
2336 makeStackTraceLong(e, self);
2337 oldOnError.call(o, e);
2338 };
2339
2340 return subscribe.call(self, o);
2341 };
2342 }
2343
2344 function Observable() {
2345 if (Rx.config.longStackSupport && hasStacks) {
2346 var oldSubscribe = this._subscribe;
2347 var e = tryCatch(thrower)(new Error()).e;
2348 this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
2349 this._subscribe = makeSubscribe(this, oldSubscribe);
2350 }
2351 }
2352
2353 observableProto = Observable.prototype;
2354
2355 /**
2356 * Determines whether the given object is an Observable
2357 * @param {Any} An object to determine whether it is an Observable
2358 * @returns {Boolean} true if an Observable, else false.
2359 */
2360 Observable.isObservable = function (o) {
2361 return o && isFunction(o.subscribe);
2362 };
2363
2364 /**
2365 * Subscribes an o to the observable sequence.
2366 * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
2367 * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
2368 * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
2369 * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
2370 */
2371 observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
2372 return this._subscribe(typeof oOrOnNext === 'object' ?
2373 oOrOnNext :
2374 observerCreate(oOrOnNext, onError, onCompleted));
2375 };
2376
2377 /**
2378 * Subscribes to the next value in the sequence with an optional "this" argument.
2379 * @param {Function} onNext The function to invoke on each element in the observable sequence.
2380 * @param {Any} [thisArg] Object to use as this when executing callback.
2381 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2382 */
2383 observableProto.subscribeOnNext = function (onNext, thisArg) {
2384 return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
2385 };
2386
2387 /**
2388 * Subscribes to an exceptional condition in the sequence with an optional "this" argument.
2389 * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
2390 * @param {Any} [thisArg] Object to use as this when executing callback.
2391 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2392 */
2393 observableProto.subscribeOnError = function (onError, thisArg) {
2394 return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
2395 };
2396
2397 /**
2398 * Subscribes to the next value in the sequence with an optional "this" argument.
2399 * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
2400 * @param {Any} [thisArg] Object to use as this when executing callback.
2401 * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
2402 */
2403 observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
2404 return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
2405 };
2406
2407 return Observable;
2408 })();
2409
2410 var ObservableBase = Rx.ObservableBase = (function (__super__) {
2411 inherits(ObservableBase, __super__);
2412
2413 function fixSubscriber(subscriber) {
2414 return subscriber && isFunction(subscriber.dispose) ? subscriber :
2415 isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
2416 }
2417
2418 function setDisposable(s, state) {
2419 var ado = state[0], self = state[1];
2420 var sub = tryCatch(self.subscribeCore).call(self, ado);
2421 if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
2422 ado.setDisposable(fixSubscriber(sub));
2423 }
2424
2425 function ObservableBase() {
2426 __super__.call(this);
2427 }
2428
2429 ObservableBase.prototype._subscribe = function (o) {
2430 var ado = new AutoDetachObserver(o), state = [ado, this];
2431
2432 if (currentThreadScheduler.scheduleRequired()) {
2433 currentThreadScheduler.schedule(state, setDisposable);
2434 } else {
2435 setDisposable(null, state);
2436 }
2437 return ado;
2438 };
2439
2440 ObservableBase.prototype.subscribeCore = notImplemented;
2441
2442 return ObservableBase;
2443 }(Observable));
2444
2445var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {
2446
2447 inherits(FlatMapObservable, __super__);
2448
2449 function FlatMapObservable(source, selector, resultSelector, thisArg) {
2450 this.resultSelector = isFunction(resultSelector) ? resultSelector : null;
2451 this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
2452 this.source = source;
2453 __super__.call(this);
2454 }
2455
2456 FlatMapObservable.prototype.subscribeCore = function(o) {
2457 return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
2458 };
2459
2460 inherits(InnerObserver, AbstractObserver);
2461 function InnerObserver(observer, selector, resultSelector, source) {
2462 this.i = 0;
2463 this.selector = selector;
2464 this.resultSelector = resultSelector;
2465 this.source = source;
2466 this.o = observer;
2467 AbstractObserver.call(this);
2468 }
2469
2470 InnerObserver.prototype._wrapResult = function(result, x, i) {
2471 return this.resultSelector ?
2472 result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
2473 result;
2474 };
2475
2476 InnerObserver.prototype.next = function(x) {
2477 var i = this.i++;
2478 var result = tryCatch(this.selector)(x, i, this.source);
2479 if (result === errorObj) { return this.o.onError(result.e); }
2480
2481 isPromise(result) && (result = observableFromPromise(result));
2482 (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));
2483 this.o.onNext(this._wrapResult(result, x, i));
2484 };
2485
2486 InnerObserver.prototype.error = function(e) { this.o.onError(e); };
2487
2488 InnerObserver.prototype.completed = function() { this.o.onCompleted(); };
2489
2490 return FlatMapObservable;
2491
2492}(ObservableBase));
2493
2494 var Enumerable = Rx.internals.Enumerable = function () { };
2495
2496 function IsDisposedDisposable(state) {
2497 this._s = state;
2498 this.isDisposed = false;
2499 }
2500
2501 IsDisposedDisposable.prototype.dispose = function () {
2502 if (!this.isDisposed) {
2503 this.isDisposed = true;
2504 this._s.isDisposed = true;
2505 }
2506 };
2507
2508 var ConcatEnumerableObservable = (function(__super__) {
2509 inherits(ConcatEnumerableObservable, __super__);
2510 function ConcatEnumerableObservable(sources) {
2511 this.sources = sources;
2512 __super__.call(this);
2513 }
2514
2515 function scheduleMethod(state, recurse) {
2516 if (state.isDisposed) { return; }
2517 var currentItem = tryCatch(state.e.next).call(state.e);
2518 if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
2519 if (currentItem.done) { return state.o.onCompleted(); }
2520
2521 // Check if promise
2522 var currentValue = currentItem.value;
2523 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2524
2525 var d = new SingleAssignmentDisposable();
2526 state.subscription.setDisposable(d);
2527 d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
2528 }
2529
2530 ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
2531 var subscription = new SerialDisposable();
2532 var state = {
2533 isDisposed: false,
2534 o: o,
2535 subscription: subscription,
2536 e: this.sources[$iterator$]()
2537 };
2538
2539 var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
2540 return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
2541 };
2542
2543 function InnerObserver(state, recurse) {
2544 this._state = state;
2545 this._recurse = recurse;
2546 AbstractObserver.call(this);
2547 }
2548
2549 inherits(InnerObserver, AbstractObserver);
2550
2551 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
2552 InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };
2553 InnerObserver.prototype.completed = function () { this._recurse(this._state); };
2554
2555 return ConcatEnumerableObservable;
2556 }(ObservableBase));
2557
2558 Enumerable.prototype.concat = function () {
2559 return new ConcatEnumerableObservable(this);
2560 };
2561
2562 var CatchErrorObservable = (function(__super__) {
2563 function CatchErrorObservable(sources) {
2564 this.sources = sources;
2565 __super__.call(this);
2566 }
2567
2568 inherits(CatchErrorObservable, __super__);
2569
2570 function scheduleMethod(state, recurse) {
2571 if (state.isDisposed) { return; }
2572 var currentItem = tryCatch(state.e.next).call(state.e);
2573 if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
2574 if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }
2575
2576 var currentValue = currentItem.value;
2577 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2578
2579 var d = new SingleAssignmentDisposable();
2580 state.subscription.setDisposable(d);
2581 d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
2582 }
2583
2584 CatchErrorObservable.prototype.subscribeCore = function (o) {
2585 var subscription = new SerialDisposable();
2586 var state = {
2587 isDisposed: false,
2588 e: this.sources[$iterator$](),
2589 subscription: subscription,
2590 lastError: null,
2591 o: o
2592 };
2593
2594 var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
2595 return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
2596 };
2597
2598 function InnerObserver(state, recurse) {
2599 this._state = state;
2600 this._recurse = recurse;
2601 AbstractObserver.call(this);
2602 }
2603
2604 inherits(InnerObserver, AbstractObserver);
2605
2606 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
2607 InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };
2608 InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };
2609
2610 return CatchErrorObservable;
2611 }(ObservableBase));
2612
2613 Enumerable.prototype.catchError = function () {
2614 return new CatchErrorObservable(this);
2615 };
2616
2617 Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
2618 var sources = this;
2619 return new AnonymousObservable(function (o) {
2620 var exceptions = new Subject(),
2621 notifier = new Subject(),
2622 handled = notificationHandler(exceptions),
2623 notificationDisposable = handled.subscribe(notifier);
2624
2625 var e = sources[$iterator$]();
2626
2627 var state = { isDisposed: false },
2628 lastError,
2629 subscription = new SerialDisposable();
2630 var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, self) {
2631 if (state.isDisposed) { return; }
2632 var currentItem = tryCatch(e.next).call(e);
2633 if (currentItem === errorObj) { return o.onError(currentItem.e); }
2634
2635 if (currentItem.done) {
2636 if (lastError) {
2637 o.onError(lastError);
2638 } else {
2639 o.onCompleted();
2640 }
2641 return;
2642 }
2643
2644 // Check if promise
2645 var currentValue = currentItem.value;
2646 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
2647
2648 var outer = new SingleAssignmentDisposable();
2649 var inner = new SingleAssignmentDisposable();
2650 subscription.setDisposable(new BinaryDisposable(inner, outer));
2651 outer.setDisposable(currentValue.subscribe(
2652 function(x) { o.onNext(x); },
2653 function (exn) {
2654 inner.setDisposable(notifier.subscribe(self, function(ex) {
2655 o.onError(ex);
2656 }, function() {
2657 o.onCompleted();
2658 }));
2659
2660 exceptions.onNext(exn);
2661 },
2662 function() { o.onCompleted(); }));
2663 });
2664
2665 return new NAryDisposable([notificationDisposable, subscription, cancelable, new IsDisposedDisposable(state)]);
2666 });
2667 };
2668
2669 var RepeatEnumerable = (function (__super__) {
2670 inherits(RepeatEnumerable, __super__);
2671 function RepeatEnumerable(v, c) {
2672 this.v = v;
2673 this.c = c == null ? -1 : c;
2674 }
2675
2676 RepeatEnumerable.prototype[$iterator$] = function () {
2677 return new RepeatEnumerator(this);
2678 };
2679
2680 function RepeatEnumerator(p) {
2681 this.v = p.v;
2682 this.l = p.c;
2683 }
2684
2685 RepeatEnumerator.prototype.next = function () {
2686 if (this.l === 0) { return doneEnumerator; }
2687 if (this.l > 0) { this.l--; }
2688 return { done: false, value: this.v };
2689 };
2690
2691 return RepeatEnumerable;
2692 }(Enumerable));
2693
2694 var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
2695 return new RepeatEnumerable(value, repeatCount);
2696 };
2697
2698 var OfEnumerable = (function(__super__) {
2699 inherits(OfEnumerable, __super__);
2700 function OfEnumerable(s, fn, thisArg) {
2701 this.s = s;
2702 this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
2703 }
2704 OfEnumerable.prototype[$iterator$] = function () {
2705 return new OfEnumerator(this);
2706 };
2707
2708 function OfEnumerator(p) {
2709 this.i = -1;
2710 this.s = p.s;
2711 this.l = this.s.length;
2712 this.fn = p.fn;
2713 }
2714
2715 OfEnumerator.prototype.next = function () {
2716 return ++this.i < this.l ?
2717 { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
2718 doneEnumerator;
2719 };
2720
2721 return OfEnumerable;
2722 }(Enumerable));
2723
2724 var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
2725 return new OfEnumerable(source, selector, thisArg);
2726 };
2727
2728var ObserveOnObservable = (function (__super__) {
2729 inherits(ObserveOnObservable, __super__);
2730 function ObserveOnObservable(source, s) {
2731 this.source = source;
2732 this._s = s;
2733 __super__.call(this);
2734 }
2735
2736 ObserveOnObservable.prototype.subscribeCore = function (o) {
2737 return this.source.subscribe(new ObserveOnObserver(this._s, o));
2738 };
2739
2740 return ObserveOnObservable;
2741}(ObservableBase));
2742
2743 /**
2744 * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
2745 *
2746 * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
2747 * that require to be run on a scheduler, use subscribeOn.
2748 *
2749 * @param {Scheduler} scheduler Scheduler to notify observers on.
2750 * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
2751 */
2752 observableProto.observeOn = function (scheduler) {
2753 return new ObserveOnObservable(this, scheduler);
2754 };
2755
2756 var SubscribeOnObservable = (function (__super__) {
2757 inherits(SubscribeOnObservable, __super__);
2758 function SubscribeOnObservable(source, s) {
2759 this.source = source;
2760 this._s = s;
2761 __super__.call(this);
2762 }
2763
2764 function scheduleMethod(scheduler, state) {
2765 var source = state[0], d = state[1], o = state[2];
2766 d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
2767 }
2768
2769 SubscribeOnObservable.prototype.subscribeCore = function (o) {
2770 var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
2771 d.setDisposable(m);
2772 m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
2773 return d;
2774 };
2775
2776 return SubscribeOnObservable;
2777 }(ObservableBase));
2778
2779 /**
2780 * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
2781 * see the remarks section for more information on the distinction between subscribeOn and observeOn.
2782
2783 * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
2784 * callbacks on a scheduler, use observeOn.
2785
2786 * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
2787 * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
2788 */
2789 observableProto.subscribeOn = function (scheduler) {
2790 return new SubscribeOnObservable(this, scheduler);
2791 };
2792
2793 var FromPromiseObservable = (function(__super__) {
2794 inherits(FromPromiseObservable, __super__);
2795 function FromPromiseObservable(p, s) {
2796 this._p = p;
2797 this._s = s;
2798 __super__.call(this);
2799 }
2800
2801 function scheduleNext(s, state) {
2802 var o = state[0], data = state[1];
2803 o.onNext(data);
2804 o.onCompleted();
2805 }
2806
2807 function scheduleError(s, state) {
2808 var o = state[0], err = state[1];
2809 o.onError(err);
2810 }
2811
2812 FromPromiseObservable.prototype.subscribeCore = function(o) {
2813 var sad = new SingleAssignmentDisposable(), self = this;
2814
2815 this._p
2816 .then(function (data) {
2817 sad.setDisposable(self._s.schedule([o, data], scheduleNext));
2818 }, function (err) {
2819 sad.setDisposable(self._s.schedule([o, err], scheduleError));
2820 });
2821
2822 return sad;
2823 };
2824
2825 return FromPromiseObservable;
2826 }(ObservableBase));
2827
2828 /**
2829 * Converts a Promise to an Observable sequence
2830 * @param {Promise} An ES6 Compliant promise.
2831 * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
2832 */
2833 var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {
2834 scheduler || (scheduler = defaultScheduler);
2835 return new FromPromiseObservable(promise, scheduler);
2836 };
2837
2838 /*
2839 * Converts an existing observable sequence to an ES6 Compatible Promise
2840 * @example
2841 * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
2842 *
2843 * // With config
2844 * Rx.config.Promise = RSVP.Promise;
2845 * var promise = Rx.Observable.return(42).toPromise();
2846 * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
2847 * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
2848 */
2849 observableProto.toPromise = function (promiseCtor) {
2850 promiseCtor || (promiseCtor = Rx.config.Promise);
2851 if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
2852 var source = this;
2853 return new promiseCtor(function (resolve, reject) {
2854 // No cancellation can be done
2855 var value;
2856 source.subscribe(function (v) {
2857 value = v;
2858 }, reject, function () {
2859 resolve(value);
2860 });
2861 });
2862 };
2863
2864 var ToArrayObservable = (function(__super__) {
2865 inherits(ToArrayObservable, __super__);
2866 function ToArrayObservable(source) {
2867 this.source = source;
2868 __super__.call(this);
2869 }
2870
2871 ToArrayObservable.prototype.subscribeCore = function(o) {
2872 return this.source.subscribe(new InnerObserver(o));
2873 };
2874
2875 inherits(InnerObserver, AbstractObserver);
2876 function InnerObserver(o) {
2877 this.o = o;
2878 this.a = [];
2879 AbstractObserver.call(this);
2880 }
2881
2882 InnerObserver.prototype.next = function (x) { this.a.push(x); };
2883 InnerObserver.prototype.error = function (e) { this.o.onError(e); };
2884 InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };
2885
2886 return ToArrayObservable;
2887 }(ObservableBase));
2888
2889 /**
2890 * Creates an array from an observable sequence.
2891 * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
2892 */
2893 observableProto.toArray = function () {
2894 return new ToArrayObservable(this);
2895 };
2896
2897 /**
2898 * Creates an observable sequence from a specified subscribe method implementation.
2899 * @example
2900 * var res = Rx.Observable.create(function (observer) { return function () { } );
2901 * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
2902 * var res = Rx.Observable.create(function (observer) { } );
2903 * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
2904 * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
2905 */
2906 Observable.create = function (subscribe, parent) {
2907 return new AnonymousObservable(subscribe, parent);
2908 };
2909
2910 var Defer = (function(__super__) {
2911 inherits(Defer, __super__);
2912 function Defer(factory) {
2913 this._f = factory;
2914 __super__.call(this);
2915 }
2916
2917 Defer.prototype.subscribeCore = function (o) {
2918 var result = tryCatch(this._f)();
2919 if (result === errorObj) { return observableThrow(result.e).subscribe(o);}
2920 isPromise(result) && (result = observableFromPromise(result));
2921 return result.subscribe(o);
2922 };
2923
2924 return Defer;
2925 }(ObservableBase));
2926
2927 /**
2928 * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
2929 *
2930 * @example
2931 * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
2932 * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
2933 * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
2934 */
2935 var observableDefer = Observable.defer = function (observableFactory) {
2936 return new Defer(observableFactory);
2937 };
2938
2939 var EmptyObservable = (function(__super__) {
2940 inherits(EmptyObservable, __super__);
2941 function EmptyObservable(scheduler) {
2942 this.scheduler = scheduler;
2943 __super__.call(this);
2944 }
2945
2946 EmptyObservable.prototype.subscribeCore = function (observer) {
2947 var sink = new EmptySink(observer, this.scheduler);
2948 return sink.run();
2949 };
2950
2951 function EmptySink(observer, scheduler) {
2952 this.observer = observer;
2953 this.scheduler = scheduler;
2954 }
2955
2956 function scheduleItem(s, state) {
2957 state.onCompleted();
2958 return disposableEmpty;
2959 }
2960
2961 EmptySink.prototype.run = function () {
2962 var state = this.observer;
2963 return this.scheduler === immediateScheduler ?
2964 scheduleItem(null, state) :
2965 this.scheduler.schedule(state, scheduleItem);
2966 };
2967
2968 return EmptyObservable;
2969 }(ObservableBase));
2970
2971 var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
2972
2973 /**
2974 * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
2975 *
2976 * @example
2977 * var res = Rx.Observable.empty();
2978 * var res = Rx.Observable.empty(Rx.Scheduler.timeout);
2979 * @param {Scheduler} [scheduler] Scheduler to send the termination call on.
2980 * @returns {Observable} An observable sequence with no elements.
2981 */
2982 var observableEmpty = Observable.empty = function (scheduler) {
2983 isScheduler(scheduler) || (scheduler = immediateScheduler);
2984 return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
2985 };
2986
2987 var FromObservable = (function(__super__) {
2988 inherits(FromObservable, __super__);
2989 function FromObservable(iterable, fn, scheduler) {
2990 this._iterable = iterable;
2991 this._fn = fn;
2992 this._scheduler = scheduler;
2993 __super__.call(this);
2994 }
2995
2996 function createScheduleMethod(o, it, fn) {
2997 return function loopRecursive(i, recurse) {
2998 var next = tryCatch(it.next).call(it);
2999 if (next === errorObj) { return o.onError(next.e); }
3000 if (next.done) { return o.onCompleted(); }
3001
3002 var result = next.value;
3003
3004 if (isFunction(fn)) {
3005 result = tryCatch(fn)(result, i);
3006 if (result === errorObj) { return o.onError(result.e); }
3007 }
3008
3009 o.onNext(result);
3010 recurse(i + 1);
3011 };
3012 }
3013
3014 FromObservable.prototype.subscribeCore = function (o) {
3015 var list = Object(this._iterable),
3016 it = getIterable(list);
3017
3018 return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));
3019 };
3020
3021 return FromObservable;
3022 }(ObservableBase));
3023
3024 var maxSafeInteger = Math.pow(2, 53) - 1;
3025
3026 function StringIterable(s) {
3027 this._s = s;
3028 }
3029
3030 StringIterable.prototype[$iterator$] = function () {
3031 return new StringIterator(this._s);
3032 };
3033
3034 function StringIterator(s) {
3035 this._s = s;
3036 this._l = s.length;
3037 this._i = 0;
3038 }
3039
3040 StringIterator.prototype[$iterator$] = function () {
3041 return this;
3042 };
3043
3044 StringIterator.prototype.next = function () {
3045 return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
3046 };
3047
3048 function ArrayIterable(a) {
3049 this._a = a;
3050 }
3051
3052 ArrayIterable.prototype[$iterator$] = function () {
3053 return new ArrayIterator(this._a);
3054 };
3055
3056 function ArrayIterator(a) {
3057 this._a = a;
3058 this._l = toLength(a);
3059 this._i = 0;
3060 }
3061
3062 ArrayIterator.prototype[$iterator$] = function () {
3063 return this;
3064 };
3065
3066 ArrayIterator.prototype.next = function () {
3067 return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
3068 };
3069
3070 function numberIsFinite(value) {
3071 return typeof value === 'number' && root.isFinite(value);
3072 }
3073
3074 function isNan(n) {
3075 return n !== n;
3076 }
3077
3078 function getIterable(o) {
3079 var i = o[$iterator$], it;
3080 if (!i && typeof o === 'string') {
3081 it = new StringIterable(o);
3082 return it[$iterator$]();
3083 }
3084 if (!i && o.length !== undefined) {
3085 it = new ArrayIterable(o);
3086 return it[$iterator$]();
3087 }
3088 if (!i) { throw new TypeError('Object is not iterable'); }
3089 return o[$iterator$]();
3090 }
3091
3092 function sign(value) {
3093 var number = +value;
3094 if (number === 0) { return number; }
3095 if (isNaN(number)) { return number; }
3096 return number < 0 ? -1 : 1;
3097 }
3098
3099 function toLength(o) {
3100 var len = +o.length;
3101 if (isNaN(len)) { return 0; }
3102 if (len === 0 || !numberIsFinite(len)) { return len; }
3103 len = sign(len) * Math.floor(Math.abs(len));
3104 if (len <= 0) { return 0; }
3105 if (len > maxSafeInteger) { return maxSafeInteger; }
3106 return len;
3107 }
3108
3109 /**
3110 * This method creates a new Observable sequence from an array-like or iterable object.
3111 * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
3112 * @param {Function} [mapFn] Map function to call on every element of the array.
3113 * @param {Any} [thisArg] The context to use calling the mapFn if provided.
3114 * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
3115 */
3116 var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
3117 if (iterable == null) {
3118 throw new Error('iterable cannot be null.')
3119 }
3120 if (mapFn && !isFunction(mapFn)) {
3121 throw new Error('mapFn when provided must be a function');
3122 }
3123 if (mapFn) {
3124 var mapper = bindCallback(mapFn, thisArg, 2);
3125 }
3126 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3127 return new FromObservable(iterable, mapper, scheduler);
3128 }
3129
3130 var FromArrayObservable = (function(__super__) {
3131 inherits(FromArrayObservable, __super__);
3132 function FromArrayObservable(args, scheduler) {
3133 this._args = args;
3134 this._scheduler = scheduler;
3135 __super__.call(this);
3136 }
3137
3138 function scheduleMethod(o, args) {
3139 var len = args.length;
3140 return function loopRecursive (i, recurse) {
3141 if (i < len) {
3142 o.onNext(args[i]);
3143 recurse(i + 1);
3144 } else {
3145 o.onCompleted();
3146 }
3147 };
3148 }
3149
3150 FromArrayObservable.prototype.subscribeCore = function (o) {
3151 return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));
3152 };
3153
3154 return FromArrayObservable;
3155 }(ObservableBase));
3156
3157 /**
3158 * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
3159 * @deprecated use Observable.from or Observable.of
3160 * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
3161 * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
3162 */
3163 var observableFromArray = Observable.fromArray = function (array, scheduler) {
3164 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3165 return new FromArrayObservable(array, scheduler)
3166 };
3167
3168 var GenerateObservable = (function (__super__) {
3169 inherits(GenerateObservable, __super__);
3170 function GenerateObservable(state, cndFn, itrFn, resFn, s) {
3171 this._state = state;
3172 this._cndFn = cndFn;
3173 this._itrFn = itrFn;
3174 this._resFn = resFn;
3175 this._s = s;
3176 this._first = true;
3177 __super__.call(this);
3178 }
3179
3180 function scheduleRecursive(self, recurse) {
3181 if (self._first) {
3182 self._first = false;
3183 } else {
3184 self._state = tryCatch(self._itrFn)(self._state);
3185 if (self._state === errorObj) { return self._o.onError(self._state.e); }
3186 }
3187 var hasResult = tryCatch(self._cndFn)(self._state);
3188 if (hasResult === errorObj) { return self._o.onError(hasResult.e); }
3189 if (hasResult) {
3190 var result = tryCatch(self._resFn)(self._state);
3191 if (result === errorObj) { return self._o.onError(result.e); }
3192 self._o.onNext(result);
3193 recurse(self);
3194 } else {
3195 self._o.onCompleted();
3196 }
3197 }
3198
3199 GenerateObservable.prototype.subscribeCore = function (o) {
3200 this._o = o;
3201 return this._s.scheduleRecursive(this, scheduleRecursive);
3202 };
3203
3204 return GenerateObservable;
3205 }(ObservableBase));
3206
3207 /**
3208 * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
3209 *
3210 * @example
3211 * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
3212 * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
3213 * @param {Mixed} initialState Initial state.
3214 * @param {Function} condition Condition to terminate generation (upon returning false).
3215 * @param {Function} iterate Iteration step function.
3216 * @param {Function} resultSelector Selector function for results produced in the sequence.
3217 * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
3218 * @returns {Observable} The generated sequence.
3219 */
3220 Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
3221 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3222 return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
3223 };
3224
3225 function observableOf (scheduler, array) {
3226 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3227 return new FromArrayObservable(array, scheduler);
3228 }
3229
3230 /**
3231 * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
3232 * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
3233 */
3234 Observable.of = function () {
3235 var len = arguments.length, args = new Array(len);
3236 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3237 return new FromArrayObservable(args, currentThreadScheduler);
3238 };
3239
3240 /**
3241 * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
3242 * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
3243 * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
3244 */
3245 Observable.ofWithScheduler = function (scheduler) {
3246 var len = arguments.length, args = new Array(len - 1);
3247 for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
3248 return new FromArrayObservable(args, scheduler);
3249 };
3250
3251 var NeverObservable = (function(__super__) {
3252 inherits(NeverObservable, __super__);
3253 function NeverObservable() {
3254 __super__.call(this);
3255 }
3256
3257 NeverObservable.prototype.subscribeCore = function (observer) {
3258 return disposableEmpty;
3259 };
3260
3261 return NeverObservable;
3262 }(ObservableBase));
3263
3264 var NEVER_OBSERVABLE = new NeverObservable();
3265
3266 /**
3267 * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
3268 * @returns {Observable} An observable sequence whose observers will never get called.
3269 */
3270 var observableNever = Observable.never = function () {
3271 return NEVER_OBSERVABLE;
3272 };
3273
3274 var PairsObservable = (function(__super__) {
3275 inherits(PairsObservable, __super__);
3276 function PairsObservable(o, scheduler) {
3277 this._o = o;
3278 this._keys = Object.keys(o);
3279 this._scheduler = scheduler;
3280 __super__.call(this);
3281 }
3282
3283 function scheduleMethod(o, obj, keys) {
3284 return function loopRecursive(i, recurse) {
3285 if (i < keys.length) {
3286 var key = keys[i];
3287 o.onNext([key, obj[key]]);
3288 recurse(i + 1);
3289 } else {
3290 o.onCompleted();
3291 }
3292 };
3293 }
3294
3295 PairsObservable.prototype.subscribeCore = function (o) {
3296 return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));
3297 };
3298
3299 return PairsObservable;
3300 }(ObservableBase));
3301
3302 /**
3303 * Convert an object into an observable sequence of [key, value] pairs.
3304 * @param {Object} obj The object to inspect.
3305 * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
3306 * @returns {Observable} An observable sequence of [key, value] pairs from the object.
3307 */
3308 Observable.pairs = function (obj, scheduler) {
3309 scheduler || (scheduler = currentThreadScheduler);
3310 return new PairsObservable(obj, scheduler);
3311 };
3312
3313 var RangeObservable = (function(__super__) {
3314 inherits(RangeObservable, __super__);
3315 function RangeObservable(start, count, scheduler) {
3316 this.start = start;
3317 this.rangeCount = count;
3318 this.scheduler = scheduler;
3319 __super__.call(this);
3320 }
3321
3322 function loopRecursive(start, count, o) {
3323 return function loop (i, recurse) {
3324 if (i < count) {
3325 o.onNext(start + i);
3326 recurse(i + 1);
3327 } else {
3328 o.onCompleted();
3329 }
3330 };
3331 }
3332
3333 RangeObservable.prototype.subscribeCore = function (o) {
3334 return this.scheduler.scheduleRecursive(
3335 0,
3336 loopRecursive(this.start, this.rangeCount, o)
3337 );
3338 };
3339
3340 return RangeObservable;
3341 }(ObservableBase));
3342
3343 /**
3344 * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
3345 * @param {Number} start The value of the first integer in the sequence.
3346 * @param {Number} count The number of sequential integers to generate.
3347 * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
3348 * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
3349 */
3350 Observable.range = function (start, count, scheduler) {
3351 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3352 return new RangeObservable(start, count, scheduler);
3353 };
3354
3355 var RepeatObservable = (function(__super__) {
3356 inherits(RepeatObservable, __super__);
3357 function RepeatObservable(value, repeatCount, scheduler) {
3358 this.value = value;
3359 this.repeatCount = repeatCount == null ? -1 : repeatCount;
3360 this.scheduler = scheduler;
3361 __super__.call(this);
3362 }
3363
3364 RepeatObservable.prototype.subscribeCore = function (observer) {
3365 var sink = new RepeatSink(observer, this);
3366 return sink.run();
3367 };
3368
3369 return RepeatObservable;
3370 }(ObservableBase));
3371
3372 function RepeatSink(observer, parent) {
3373 this.observer = observer;
3374 this.parent = parent;
3375 }
3376
3377 RepeatSink.prototype.run = function () {
3378 var observer = this.observer, value = this.parent.value;
3379 function loopRecursive(i, recurse) {
3380 if (i === -1 || i > 0) {
3381 observer.onNext(value);
3382 i > 0 && i--;
3383 }
3384 if (i === 0) { return observer.onCompleted(); }
3385 recurse(i);
3386 }
3387
3388 return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
3389 };
3390
3391 /**
3392 * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
3393 * @param {Mixed} value Element to repeat.
3394 * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
3395 * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
3396 * @returns {Observable} An observable sequence that repeats the given element the specified number of times.
3397 */
3398 Observable.repeat = function (value, repeatCount, scheduler) {
3399 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
3400 return new RepeatObservable(value, repeatCount, scheduler);
3401 };
3402
3403 var JustObservable = (function(__super__) {
3404 inherits(JustObservable, __super__);
3405 function JustObservable(value, scheduler) {
3406 this._value = value;
3407 this._scheduler = scheduler;
3408 __super__.call(this);
3409 }
3410
3411 JustObservable.prototype.subscribeCore = function (o) {
3412 var state = [this._value, o];
3413 return this._scheduler === immediateScheduler ?
3414 scheduleItem(null, state) :
3415 this._scheduler.schedule(state, scheduleItem);
3416 };
3417
3418 function scheduleItem(s, state) {
3419 var value = state[0], observer = state[1];
3420 observer.onNext(value);
3421 observer.onCompleted();
3422 return disposableEmpty;
3423 }
3424
3425 return JustObservable;
3426 }(ObservableBase));
3427
3428 /**
3429 * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
3430 * There is an alias called 'just' or browsers <IE9.
3431 * @param {Mixed} value Single element in the resulting observable sequence.
3432 * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
3433 * @returns {Observable} An observable sequence containing the single specified element.
3434 */
3435 var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
3436 isScheduler(scheduler) || (scheduler = immediateScheduler);
3437 return new JustObservable(value, scheduler);
3438 };
3439
3440 var ThrowObservable = (function(__super__) {
3441 inherits(ThrowObservable, __super__);
3442 function ThrowObservable(error, scheduler) {
3443 this._error = error;
3444 this._scheduler = scheduler;
3445 __super__.call(this);
3446 }
3447
3448 ThrowObservable.prototype.subscribeCore = function (o) {
3449 var state = [this._error, o];
3450 return this._scheduler === immediateScheduler ?
3451 scheduleItem(null, state) :
3452 this._scheduler.schedule(state, scheduleItem);
3453 };
3454
3455 function scheduleItem(s, state) {
3456 var e = state[0], o = state[1];
3457 o.onError(e);
3458 return disposableEmpty;
3459 }
3460
3461 return ThrowObservable;
3462 }(ObservableBase));
3463
3464 /**
3465 * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
3466 * There is an alias to this method called 'throwError' for browsers <IE9.
3467 * @param {Mixed} error An object used for the sequence's termination.
3468 * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
3469 * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
3470 */
3471 var observableThrow = Observable['throw'] = function (error, scheduler) {
3472 isScheduler(scheduler) || (scheduler = immediateScheduler);
3473 return new ThrowObservable(error, scheduler);
3474 };
3475
3476 var UsingObservable = (function (__super__) {
3477 inherits(UsingObservable, __super__);
3478 function UsingObservable(resFn, obsFn) {
3479 this._resFn = resFn;
3480 this._obsFn = obsFn;
3481 __super__.call(this);
3482 }
3483
3484 UsingObservable.prototype.subscribeCore = function (o) {
3485 var disposable = disposableEmpty;
3486 var resource = tryCatch(this._resFn)();
3487 if (resource === errorObj) {
3488 return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
3489 }
3490 resource && (disposable = resource);
3491 var source = tryCatch(this._obsFn)(resource);
3492 if (source === errorObj) {
3493 return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
3494 }
3495 return new BinaryDisposable(source.subscribe(o), disposable);
3496 };
3497
3498 return UsingObservable;
3499 }(ObservableBase));
3500
3501 /**
3502 * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
3503 * @param {Function} resourceFactory Factory function to obtain a resource object.
3504 * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
3505 * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
3506 */
3507 Observable.using = function (resourceFactory, observableFactory) {
3508 return new UsingObservable(resourceFactory, observableFactory);
3509 };
3510
3511 /**
3512 * Propagates the observable sequence or Promise that reacts first.
3513 * @param {Observable} rightSource Second observable sequence or Promise.
3514 * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
3515 */
3516 observableProto.amb = function (rightSource) {
3517 var leftSource = this;
3518 return new AnonymousObservable(function (observer) {
3519 var choice,
3520 leftChoice = 'L', rightChoice = 'R',
3521 leftSubscription = new SingleAssignmentDisposable(),
3522 rightSubscription = new SingleAssignmentDisposable();
3523
3524 isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
3525
3526 function choiceL() {
3527 if (!choice) {
3528 choice = leftChoice;
3529 rightSubscription.dispose();
3530 }
3531 }
3532
3533 function choiceR() {
3534 if (!choice) {
3535 choice = rightChoice;
3536 leftSubscription.dispose();
3537 }
3538 }
3539
3540 var leftSubscribe = observerCreate(
3541 function (left) {
3542 choiceL();
3543 choice === leftChoice && observer.onNext(left);
3544 },
3545 function (e) {
3546 choiceL();
3547 choice === leftChoice && observer.onError(e);
3548 },
3549 function () {
3550 choiceL();
3551 choice === leftChoice && observer.onCompleted();
3552 }
3553 );
3554 var rightSubscribe = observerCreate(
3555 function (right) {
3556 choiceR();
3557 choice === rightChoice && observer.onNext(right);
3558 },
3559 function (e) {
3560 choiceR();
3561 choice === rightChoice && observer.onError(e);
3562 },
3563 function () {
3564 choiceR();
3565 choice === rightChoice && observer.onCompleted();
3566 }
3567 );
3568
3569 leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
3570 rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
3571
3572 return new BinaryDisposable(leftSubscription, rightSubscription);
3573 });
3574 };
3575
3576 function amb(p, c) { return p.amb(c); }
3577
3578 /**
3579 * Propagates the observable sequence or Promise that reacts first.
3580 * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
3581 */
3582 Observable.amb = function () {
3583 var acc = observableNever(), items;
3584 if (Array.isArray(arguments[0])) {
3585 items = arguments[0];
3586 } else {
3587 var len = arguments.length;
3588 items = new Array(items);
3589 for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
3590 }
3591 for (var i = 0, len = items.length; i < len; i++) {
3592 acc = amb(acc, items[i]);
3593 }
3594 return acc;
3595 };
3596
3597 var CatchObservable = (function (__super__) {
3598 inherits(CatchObservable, __super__);
3599 function CatchObservable(source, fn) {
3600 this.source = source;
3601 this._fn = fn;
3602 __super__.call(this);
3603 }
3604
3605 CatchObservable.prototype.subscribeCore = function (o) {
3606 var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
3607 subscription.setDisposable(d1);
3608 d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn)));
3609 return subscription;
3610 };
3611
3612 return CatchObservable;
3613 }(ObservableBase));
3614
3615 var CatchObserver = (function(__super__) {
3616 inherits(CatchObserver, __super__);
3617 function CatchObserver(o, s, fn) {
3618 this._o = o;
3619 this._s = s;
3620 this._fn = fn;
3621 __super__.call(this);
3622 }
3623
3624 CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
3625 CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
3626 CatchObserver.prototype.error = function (e) {
3627 var result = tryCatch(this._fn)(e);
3628 if (result === errorObj) { return this._o.onError(result.e); }
3629 isPromise(result) && (result = observableFromPromise(result));
3630
3631 var d = new SingleAssignmentDisposable();
3632 this._s.setDisposable(d);
3633 d.setDisposable(result.subscribe(this._o));
3634 };
3635
3636 return CatchObserver;
3637 }(AbstractObserver));
3638
3639 /**
3640 * Continues an observable sequence that is terminated by an exception with the next observable sequence.
3641 * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
3642 * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
3643 */
3644 observableProto['catch'] = function (handlerOrSecond) {
3645 return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
3646 };
3647
3648 /**
3649 * Continues an observable sequence that is terminated by an exception with the next observable sequence.
3650 * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
3651 * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
3652 */
3653 var observableCatch = Observable['catch'] = function () {
3654 var items;
3655 if (Array.isArray(arguments[0])) {
3656 items = arguments[0];
3657 } else {
3658 var len = arguments.length;
3659 items = new Array(len);
3660 for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
3661 }
3662 return enumerableOf(items).catchError();
3663 };
3664
3665 /**
3666 * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
3667 * This can be in the form of an argument list of observables or an array.
3668 *
3669 * @example
3670 * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
3671 * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
3672 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
3673 */
3674 observableProto.combineLatest = function () {
3675 var len = arguments.length, args = new Array(len);
3676 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3677 if (Array.isArray(args[0])) {
3678 args[0].unshift(this);
3679 } else {
3680 args.unshift(this);
3681 }
3682 return combineLatest.apply(this, args);
3683 };
3684
3685 function falseFactory() { return false; }
3686 function argumentsToArray() {
3687 var len = arguments.length, args = new Array(len);
3688 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3689 return args;
3690 }
3691
3692 var CombineLatestObservable = (function(__super__) {
3693 inherits(CombineLatestObservable, __super__);
3694 function CombineLatestObservable(params, cb) {
3695 this._params = params;
3696 this._cb = cb;
3697 __super__.call(this);
3698 }
3699
3700 CombineLatestObservable.prototype.subscribeCore = function(observer) {
3701 var len = this._params.length,
3702 subscriptions = new Array(len);
3703
3704 var state = {
3705 hasValue: arrayInitialize(len, falseFactory),
3706 hasValueAll: false,
3707 isDone: arrayInitialize(len, falseFactory),
3708 values: new Array(len)
3709 };
3710
3711 for (var i = 0; i < len; i++) {
3712 var source = this._params[i], sad = new SingleAssignmentDisposable();
3713 subscriptions[i] = sad;
3714 isPromise(source) && (source = observableFromPromise(source));
3715 sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
3716 }
3717
3718 return new NAryDisposable(subscriptions);
3719 };
3720
3721 return CombineLatestObservable;
3722 }(ObservableBase));
3723
3724 var CombineLatestObserver = (function (__super__) {
3725 inherits(CombineLatestObserver, __super__);
3726 function CombineLatestObserver(o, i, cb, state) {
3727 this._o = o;
3728 this._i = i;
3729 this._cb = cb;
3730 this._state = state;
3731 __super__.call(this);
3732 }
3733
3734 function notTheSame(i) {
3735 return function (x, j) {
3736 return j !== i;
3737 };
3738 }
3739
3740 CombineLatestObserver.prototype.next = function (x) {
3741 this._state.values[this._i] = x;
3742 this._state.hasValue[this._i] = true;
3743 if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
3744 var res = tryCatch(this._cb).apply(null, this._state.values);
3745 if (res === errorObj) { return this._o.onError(res.e); }
3746 this._o.onNext(res);
3747 } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
3748 this._o.onCompleted();
3749 }
3750 };
3751
3752 CombineLatestObserver.prototype.error = function (e) {
3753 this._o.onError(e);
3754 };
3755
3756 CombineLatestObserver.prototype.completed = function () {
3757 this._state.isDone[this._i] = true;
3758 this._state.isDone.every(identity) && this._o.onCompleted();
3759 };
3760
3761 return CombineLatestObserver;
3762 }(AbstractObserver));
3763
3764 /**
3765 * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
3766 *
3767 * @example
3768 * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
3769 * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
3770 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
3771 */
3772 var combineLatest = Observable.combineLatest = function () {
3773 var len = arguments.length, args = new Array(len);
3774 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
3775 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
3776 Array.isArray(args[0]) && (args = args[0]);
3777 return new CombineLatestObservable(args, resultSelector);
3778 };
3779
3780 /**
3781 * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
3782 * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
3783 */
3784 observableProto.concat = function () {
3785 for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
3786 args.unshift(this);
3787 return observableConcat.apply(null, args);
3788 };
3789
3790 var ConcatObserver = (function(__super__) {
3791 inherits(ConcatObserver, __super__);
3792 function ConcatObserver(s, fn) {
3793 this._s = s;
3794 this._fn = fn;
3795 __super__.call(this);
3796 }
3797
3798 ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); };
3799 ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); };
3800 ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); };
3801
3802 return ConcatObserver;
3803 }(AbstractObserver));
3804
3805 var ConcatObservable = (function(__super__) {
3806 inherits(ConcatObservable, __super__);
3807 function ConcatObservable(sources) {
3808 this._sources = sources;
3809 __super__.call(this);
3810 }
3811
3812 function scheduleRecursive (state, recurse) {
3813 if (state.disposable.isDisposed) { return; }
3814 if (state.i === state.sources.length) { return state.o.onCompleted(); }
3815
3816 // Check if promise
3817 var currentValue = state.sources[state.i];
3818 isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
3819
3820 var d = new SingleAssignmentDisposable();
3821 state.subscription.setDisposable(d);
3822 d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse)));
3823 }
3824
3825 ConcatObservable.prototype.subscribeCore = function(o) {
3826 var subscription = new SerialDisposable();
3827 var disposable = disposableCreate(noop);
3828 var state = {
3829 o: o,
3830 i: 0,
3831 subscription: subscription,
3832 disposable: disposable,
3833 sources: this._sources
3834 };
3835
3836 var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive);
3837 return new NAryDisposable([subscription, disposable, cancelable]);
3838 };
3839
3840 return ConcatObservable;
3841 }(ObservableBase));
3842
3843 /**
3844 * Concatenates all the observable sequences.
3845 * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
3846 * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
3847 */
3848 var observableConcat = Observable.concat = function () {
3849 var args;
3850 if (Array.isArray(arguments[0])) {
3851 args = arguments[0];
3852 } else {
3853 args = new Array(arguments.length);
3854 for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
3855 }
3856 return new ConcatObservable(args);
3857 };
3858
3859 /**
3860 * Concatenates an observable sequence of observable sequences.
3861 * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
3862 */
3863 observableProto.concatAll = function () {
3864 return this.merge(1);
3865 };
3866
3867 var MergeObservable = (function (__super__) {
3868 inherits(MergeObservable, __super__);
3869
3870 function MergeObservable(source, maxConcurrent) {
3871 this.source = source;
3872 this.maxConcurrent = maxConcurrent;
3873 __super__.call(this);
3874 }
3875
3876 MergeObservable.prototype.subscribeCore = function(observer) {
3877 var g = new CompositeDisposable();
3878 g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
3879 return g;
3880 };
3881
3882 return MergeObservable;
3883
3884 }(ObservableBase));
3885
3886 var MergeObserver = (function (__super__) {
3887 function MergeObserver(o, max, g) {
3888 this.o = o;
3889 this.max = max;
3890 this.g = g;
3891 this.done = false;
3892 this.q = [];
3893 this.activeCount = 0;
3894 __super__.call(this);
3895 }
3896
3897 inherits(MergeObserver, __super__);
3898
3899 MergeObserver.prototype.handleSubscribe = function (xs) {
3900 var sad = new SingleAssignmentDisposable();
3901 this.g.add(sad);
3902 isPromise(xs) && (xs = observableFromPromise(xs));
3903 sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
3904 };
3905
3906 MergeObserver.prototype.next = function (innerSource) {
3907 if(this.activeCount < this.max) {
3908 this.activeCount++;
3909 this.handleSubscribe(innerSource);
3910 } else {
3911 this.q.push(innerSource);
3912 }
3913 };
3914 MergeObserver.prototype.error = function (e) { this.o.onError(e); };
3915 MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); };
3916
3917 function InnerObserver(parent, sad) {
3918 this.parent = parent;
3919 this.sad = sad;
3920 __super__.call(this);
3921 }
3922
3923 inherits(InnerObserver, __super__);
3924
3925 InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); };
3926 InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); };
3927 InnerObserver.prototype.completed = function () {
3928 this.parent.g.remove(this.sad);
3929 if (this.parent.q.length > 0) {
3930 this.parent.handleSubscribe(this.parent.q.shift());
3931 } else {
3932 this.parent.activeCount--;
3933 this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();
3934 }
3935 };
3936
3937 return MergeObserver;
3938 }(AbstractObserver));
3939
3940 /**
3941 * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
3942 * Or merges two observable sequences into a single observable sequence.
3943 * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
3944 * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
3945 */
3946 observableProto.merge = function (maxConcurrentOrOther) {
3947 return typeof maxConcurrentOrOther !== 'number' ?
3948 observableMerge(this, maxConcurrentOrOther) :
3949 new MergeObservable(this, maxConcurrentOrOther);
3950 };
3951
3952 /**
3953 * Merges all the observable sequences into a single observable sequence.
3954 * The scheduler is optional and if not specified, the immediate scheduler is used.
3955 * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
3956 */
3957 var observableMerge = Observable.merge = function () {
3958 var scheduler, sources = [], i, len = arguments.length;
3959 if (!arguments[0]) {
3960 scheduler = immediateScheduler;
3961 for(i = 1; i < len; i++) { sources.push(arguments[i]); }
3962 } else if (isScheduler(arguments[0])) {
3963 scheduler = arguments[0];
3964 for(i = 1; i < len; i++) { sources.push(arguments[i]); }
3965 } else {
3966 scheduler = immediateScheduler;
3967 for(i = 0; i < len; i++) { sources.push(arguments[i]); }
3968 }
3969 if (Array.isArray(sources[0])) {
3970 sources = sources[0];
3971 }
3972 return observableOf(scheduler, sources).mergeAll();
3973 };
3974
3975 var MergeAllObservable = (function (__super__) {
3976 inherits(MergeAllObservable, __super__);
3977
3978 function MergeAllObservable(source) {
3979 this.source = source;
3980 __super__.call(this);
3981 }
3982
3983 MergeAllObservable.prototype.subscribeCore = function (o) {
3984 var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
3985 g.add(m);
3986 m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));
3987 return g;
3988 };
3989
3990 return MergeAllObservable;
3991 }(ObservableBase));
3992
3993 var MergeAllObserver = (function (__super__) {
3994 function MergeAllObserver(o, g) {
3995 this.o = o;
3996 this.g = g;
3997 this.done = false;
3998 __super__.call(this);
3999 }
4000
4001 inherits(MergeAllObserver, __super__);
4002
4003 MergeAllObserver.prototype.next = function(innerSource) {
4004 var sad = new SingleAssignmentDisposable();
4005 this.g.add(sad);
4006 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
4007 sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
4008 };
4009
4010 MergeAllObserver.prototype.error = function (e) {
4011 this.o.onError(e);
4012 };
4013
4014 MergeAllObserver.prototype.completed = function () {
4015 this.done = true;
4016 this.g.length === 1 && this.o.onCompleted();
4017 };
4018
4019 function InnerObserver(parent, sad) {
4020 this.parent = parent;
4021 this.sad = sad;
4022 __super__.call(this);
4023 }
4024
4025 inherits(InnerObserver, __super__);
4026
4027 InnerObserver.prototype.next = function (x) {
4028 this.parent.o.onNext(x);
4029 };
4030 InnerObserver.prototype.error = function (e) {
4031 this.parent.o.onError(e);
4032 };
4033 InnerObserver.prototype.completed = function () {
4034 this.parent.g.remove(this.sad);
4035 this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();
4036 };
4037
4038 return MergeAllObserver;
4039 }(AbstractObserver));
4040
4041 /**
4042 * Merges an observable sequence of observable sequences into an observable sequence.
4043 * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
4044 */
4045 observableProto.mergeAll = function () {
4046 return new MergeAllObservable(this);
4047 };
4048
4049 var CompositeError = Rx.CompositeError = function(errors) {
4050 this.innerErrors = errors;
4051 this.message = 'This contains multiple errors. Check the innerErrors';
4052 Error.call(this);
4053 };
4054 CompositeError.prototype = Object.create(Error.prototype);
4055 CompositeError.prototype.name = 'CompositeError';
4056
4057 var MergeDelayErrorObservable = (function(__super__) {
4058 inherits(MergeDelayErrorObservable, __super__);
4059 function MergeDelayErrorObservable(source) {
4060 this.source = source;
4061 __super__.call(this);
4062 }
4063
4064 MergeDelayErrorObservable.prototype.subscribeCore = function (o) {
4065 var group = new CompositeDisposable(),
4066 m = new SingleAssignmentDisposable(),
4067 state = { isStopped: false, errors: [], o: o };
4068
4069 group.add(m);
4070 m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));
4071
4072 return group;
4073 };
4074
4075 return MergeDelayErrorObservable;
4076 }(ObservableBase));
4077
4078 var MergeDelayErrorObserver = (function(__super__) {
4079 inherits(MergeDelayErrorObserver, __super__);
4080 function MergeDelayErrorObserver(group, state) {
4081 this._group = group;
4082 this._state = state;
4083 __super__.call(this);
4084 }
4085
4086 function setCompletion(o, errors) {
4087 if (errors.length === 0) {
4088 o.onCompleted();
4089 } else if (errors.length === 1) {
4090 o.onError(errors[0]);
4091 } else {
4092 o.onError(new CompositeError(errors));
4093 }
4094 }
4095
4096 MergeDelayErrorObserver.prototype.next = function (x) {
4097 var inner = new SingleAssignmentDisposable();
4098 this._group.add(inner);
4099
4100 // Check for promises support
4101 isPromise(x) && (x = observableFromPromise(x));
4102 inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));
4103 };
4104
4105 MergeDelayErrorObserver.prototype.error = function (e) {
4106 this._state.errors.push(e);
4107 this._state.isStopped = true;
4108 this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
4109 };
4110
4111 MergeDelayErrorObserver.prototype.completed = function () {
4112 this._state.isStopped = true;
4113 this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
4114 };
4115
4116 inherits(InnerObserver, __super__);
4117 function InnerObserver(inner, group, state) {
4118 this._inner = inner;
4119 this._group = group;
4120 this._state = state;
4121 __super__.call(this);
4122 }
4123
4124 InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
4125 InnerObserver.prototype.error = function (e) {
4126 this._state.errors.push(e);
4127 this._group.remove(this._inner);
4128 this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
4129 };
4130 InnerObserver.prototype.completed = function () {
4131 this._group.remove(this._inner);
4132 this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
4133 };
4134
4135 return MergeDelayErrorObserver;
4136 }(AbstractObserver));
4137
4138 /**
4139 * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
4140 * receive all successfully emitted items from all of the source Observables without being interrupted by
4141 * an error notification from one of them.
4142 *
4143 * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
4144 * error via the Observer's onError, mergeDelayError will refrain from propagating that
4145 * error notification until all of the merged Observables have finished emitting items.
4146 * @param {Array | Arguments} args Arguments or an array to merge.
4147 * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
4148 */
4149 Observable.mergeDelayError = function() {
4150 var args;
4151 if (Array.isArray(arguments[0])) {
4152 args = arguments[0];
4153 } else {
4154 var len = arguments.length;
4155 args = new Array(len);
4156 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4157 }
4158 var source = observableOf(null, args);
4159 return new MergeDelayErrorObservable(source);
4160 };
4161
4162 /**
4163 * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
4164 * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
4165 * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
4166 */
4167 observableProto.onErrorResumeNext = function (second) {
4168 if (!second) { throw new Error('Second observable is required'); }
4169 return onErrorResumeNext([this, second]);
4170 };
4171
4172 var OnErrorResumeNextObservable = (function(__super__) {
4173 inherits(OnErrorResumeNextObservable, __super__);
4174 function OnErrorResumeNextObservable(sources) {
4175 this.sources = sources;
4176 __super__.call(this);
4177 }
4178
4179 function scheduleMethod(state, recurse) {
4180 if (state.pos < state.sources.length) {
4181 var current = state.sources[state.pos++];
4182 isPromise(current) && (current = observableFromPromise(current));
4183 var d = new SingleAssignmentDisposable();
4184 state.subscription.setDisposable(d);
4185 d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));
4186 } else {
4187 state.o.onCompleted();
4188 }
4189 }
4190
4191 OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {
4192 var subscription = new SerialDisposable(),
4193 state = {pos: 0, subscription: subscription, o: o, sources: this.sources },
4194 cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);
4195
4196 return new BinaryDisposable(subscription, cancellable);
4197 };
4198
4199 return OnErrorResumeNextObservable;
4200 }(ObservableBase));
4201
4202 var OnErrorResumeNextObserver = (function(__super__) {
4203 inherits(OnErrorResumeNextObserver, __super__);
4204 function OnErrorResumeNextObserver(state, recurse) {
4205 this._state = state;
4206 this._recurse = recurse;
4207 __super__.call(this);
4208 }
4209
4210 OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };
4211 OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };
4212 OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };
4213
4214 return OnErrorResumeNextObserver;
4215 }(AbstractObserver));
4216
4217 /**
4218 * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
4219 * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
4220 */
4221 var onErrorResumeNext = Observable.onErrorResumeNext = function () {
4222 var sources = [];
4223 if (Array.isArray(arguments[0])) {
4224 sources = arguments[0];
4225 } else {
4226 var len = arguments.length;
4227 sources = new Array(len);
4228 for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
4229 }
4230 return new OnErrorResumeNextObservable(sources);
4231 };
4232
4233 var SkipUntilObservable = (function(__super__) {
4234 inherits(SkipUntilObservable, __super__);
4235
4236 function SkipUntilObservable(source, other) {
4237 this._s = source;
4238 this._o = isPromise(other) ? observableFromPromise(other) : other;
4239 this._open = false;
4240 __super__.call(this);
4241 }
4242
4243 SkipUntilObservable.prototype.subscribeCore = function(o) {
4244 var leftSubscription = new SingleAssignmentDisposable();
4245 leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));
4246
4247 isPromise(this._o) && (this._o = observableFromPromise(this._o));
4248
4249 var rightSubscription = new SingleAssignmentDisposable();
4250 rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));
4251
4252 return new BinaryDisposable(leftSubscription, rightSubscription);
4253 };
4254
4255 return SkipUntilObservable;
4256 }(ObservableBase));
4257
4258 var SkipUntilSourceObserver = (function(__super__) {
4259 inherits(SkipUntilSourceObserver, __super__);
4260 function SkipUntilSourceObserver(o, p) {
4261 this._o = o;
4262 this._p = p;
4263 __super__.call(this);
4264 }
4265
4266 SkipUntilSourceObserver.prototype.next = function (x) {
4267 this._p._open && this._o.onNext(x);
4268 };
4269
4270 SkipUntilSourceObserver.prototype.error = function (err) {
4271 this._o.onError(err);
4272 };
4273
4274 SkipUntilSourceObserver.prototype.onCompleted = function () {
4275 this._p._open && this._o.onCompleted();
4276 };
4277
4278 return SkipUntilSourceObserver;
4279 }(AbstractObserver));
4280
4281 var SkipUntilOtherObserver = (function(__super__) {
4282 inherits(SkipUntilOtherObserver, __super__);
4283 function SkipUntilOtherObserver(o, p, r) {
4284 this._o = o;
4285 this._p = p;
4286 this._r = r;
4287 __super__.call(this);
4288 }
4289
4290 SkipUntilOtherObserver.prototype.next = function () {
4291 this._p._open = true;
4292 this._r.dispose();
4293 };
4294
4295 SkipUntilOtherObserver.prototype.error = function (err) {
4296 this._o.onError(err);
4297 };
4298
4299 SkipUntilOtherObserver.prototype.onCompleted = function () {
4300 this._r.dispose();
4301 };
4302
4303 return SkipUntilOtherObserver;
4304 }(AbstractObserver));
4305
4306 /**
4307 * Returns the values from the source observable sequence only after the other observable sequence produces a value.
4308 * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
4309 * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
4310 */
4311 observableProto.skipUntil = function (other) {
4312 return new SkipUntilObservable(this, other);
4313 };
4314
4315 var SwitchObservable = (function(__super__) {
4316 inherits(SwitchObservable, __super__);
4317 function SwitchObservable(source) {
4318 this.source = source;
4319 __super__.call(this);
4320 }
4321
4322 SwitchObservable.prototype.subscribeCore = function (o) {
4323 var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
4324 return new BinaryDisposable(s, inner);
4325 };
4326
4327 inherits(SwitchObserver, AbstractObserver);
4328 function SwitchObserver(o, inner) {
4329 this.o = o;
4330 this.inner = inner;
4331 this.stopped = false;
4332 this.latest = 0;
4333 this.hasLatest = false;
4334 AbstractObserver.call(this);
4335 }
4336
4337 SwitchObserver.prototype.next = function (innerSource) {
4338 var d = new SingleAssignmentDisposable(), id = ++this.latest;
4339 this.hasLatest = true;
4340 this.inner.setDisposable(d);
4341 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
4342 d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
4343 };
4344
4345 SwitchObserver.prototype.error = function (e) {
4346 this.o.onError(e);
4347 };
4348
4349 SwitchObserver.prototype.completed = function () {
4350 this.stopped = true;
4351 !this.hasLatest && this.o.onCompleted();
4352 };
4353
4354 inherits(InnerObserver, AbstractObserver);
4355 function InnerObserver(parent, id) {
4356 this.parent = parent;
4357 this.id = id;
4358 AbstractObserver.call(this);
4359 }
4360 InnerObserver.prototype.next = function (x) {
4361 this.parent.latest === this.id && this.parent.o.onNext(x);
4362 };
4363
4364 InnerObserver.prototype.error = function (e) {
4365 this.parent.latest === this.id && this.parent.o.onError(e);
4366 };
4367
4368 InnerObserver.prototype.completed = function () {
4369 if (this.parent.latest === this.id) {
4370 this.parent.hasLatest = false;
4371 this.parent.stopped && this.parent.o.onCompleted();
4372 }
4373 };
4374
4375 return SwitchObservable;
4376 }(ObservableBase));
4377
4378 /**
4379 * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
4380 * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
4381 */
4382 observableProto['switch'] = observableProto.switchLatest = function () {
4383 return new SwitchObservable(this);
4384 };
4385
4386 var TakeUntilObservable = (function(__super__) {
4387 inherits(TakeUntilObservable, __super__);
4388
4389 function TakeUntilObservable(source, other) {
4390 this.source = source;
4391 this.other = isPromise(other) ? observableFromPromise(other) : other;
4392 __super__.call(this);
4393 }
4394
4395 TakeUntilObservable.prototype.subscribeCore = function(o) {
4396 return new BinaryDisposable(
4397 this.source.subscribe(o),
4398 this.other.subscribe(new TakeUntilObserver(o))
4399 );
4400 };
4401
4402 return TakeUntilObservable;
4403 }(ObservableBase));
4404
4405 var TakeUntilObserver = (function(__super__) {
4406 inherits(TakeUntilObserver, __super__);
4407 function TakeUntilObserver(o) {
4408 this._o = o;
4409 __super__.call(this);
4410 }
4411
4412 TakeUntilObserver.prototype.next = function () {
4413 this._o.onCompleted();
4414 };
4415
4416 TakeUntilObserver.prototype.error = function (err) {
4417 this._o.onError(err);
4418 };
4419
4420 TakeUntilObserver.prototype.onCompleted = noop;
4421
4422 return TakeUntilObserver;
4423 }(AbstractObserver));
4424
4425 /**
4426 * Returns the values from the source observable sequence until the other observable sequence produces a value.
4427 * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
4428 * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
4429 */
4430 observableProto.takeUntil = function (other) {
4431 return new TakeUntilObservable(this, other);
4432 };
4433
4434 function falseFactory() { return false; }
4435 function argumentsToArray() {
4436 var len = arguments.length, args = new Array(len);
4437 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4438 return args;
4439 }
4440
4441 var WithLatestFromObservable = (function(__super__) {
4442 inherits(WithLatestFromObservable, __super__);
4443 function WithLatestFromObservable(source, sources, resultSelector) {
4444 this._s = source;
4445 this._ss = sources;
4446 this._cb = resultSelector;
4447 __super__.call(this);
4448 }
4449
4450 WithLatestFromObservable.prototype.subscribeCore = function (o) {
4451 var len = this._ss.length;
4452 var state = {
4453 hasValue: arrayInitialize(len, falseFactory),
4454 hasValueAll: false,
4455 values: new Array(len)
4456 };
4457
4458 var n = this._ss.length, subscriptions = new Array(n + 1);
4459 for (var i = 0; i < n; i++) {
4460 var other = this._ss[i], sad = new SingleAssignmentDisposable();
4461 isPromise(other) && (other = observableFromPromise(other));
4462 sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));
4463 subscriptions[i] = sad;
4464 }
4465
4466 var outerSad = new SingleAssignmentDisposable();
4467 outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));
4468 subscriptions[n] = outerSad;
4469
4470 return new NAryDisposable(subscriptions);
4471 };
4472
4473 return WithLatestFromObservable;
4474 }(ObservableBase));
4475
4476 var WithLatestFromOtherObserver = (function (__super__) {
4477 inherits(WithLatestFromOtherObserver, __super__);
4478 function WithLatestFromOtherObserver(o, i, state) {
4479 this._o = o;
4480 this._i = i;
4481 this._state = state;
4482 __super__.call(this);
4483 }
4484
4485 WithLatestFromOtherObserver.prototype.next = function (x) {
4486 this._state.values[this._i] = x;
4487 this._state.hasValue[this._i] = true;
4488 this._state.hasValueAll = this._state.hasValue.every(identity);
4489 };
4490
4491 WithLatestFromOtherObserver.prototype.error = function (e) {
4492 this._o.onError(e);
4493 };
4494
4495 WithLatestFromOtherObserver.prototype.completed = noop;
4496
4497 return WithLatestFromOtherObserver;
4498 }(AbstractObserver));
4499
4500 var WithLatestFromSourceObserver = (function (__super__) {
4501 inherits(WithLatestFromSourceObserver, __super__);
4502 function WithLatestFromSourceObserver(o, cb, state) {
4503 this._o = o;
4504 this._cb = cb;
4505 this._state = state;
4506 __super__.call(this);
4507 }
4508
4509 WithLatestFromSourceObserver.prototype.next = function (x) {
4510 var allValues = [x].concat(this._state.values);
4511 if (!this._state.hasValueAll) { return; }
4512 var res = tryCatch(this._cb).apply(null, allValues);
4513 if (res === errorObj) { return this._o.onError(res.e); }
4514 this._o.onNext(res);
4515 };
4516
4517 WithLatestFromSourceObserver.prototype.error = function (e) {
4518 this._o.onError(e);
4519 };
4520
4521 WithLatestFromSourceObserver.prototype.completed = function () {
4522 this._o.onCompleted();
4523 };
4524
4525 return WithLatestFromSourceObserver;
4526 }(AbstractObserver));
4527
4528 /**
4529 * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
4530 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
4531 */
4532 observableProto.withLatestFrom = function () {
4533 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4534
4535 var len = arguments.length, args = new Array(len);
4536 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4537 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4538 Array.isArray(args[0]) && (args = args[0]);
4539
4540 return new WithLatestFromObservable(this, args, resultSelector);
4541 };
4542
4543 function falseFactory() { return false; }
4544 function emptyArrayFactory() { return []; }
4545
4546 var ZipObservable = (function(__super__) {
4547 inherits(ZipObservable, __super__);
4548 function ZipObservable(sources, resultSelector) {
4549 this._s = sources;
4550 this._cb = resultSelector;
4551 __super__.call(this);
4552 }
4553
4554 ZipObservable.prototype.subscribeCore = function(observer) {
4555 var n = this._s.length,
4556 subscriptions = new Array(n),
4557 done = arrayInitialize(n, falseFactory),
4558 q = arrayInitialize(n, emptyArrayFactory);
4559
4560 for (var i = 0; i < n; i++) {
4561 var source = this._s[i], sad = new SingleAssignmentDisposable();
4562 subscriptions[i] = sad;
4563 isPromise(source) && (source = observableFromPromise(source));
4564 sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));
4565 }
4566
4567 return new NAryDisposable(subscriptions);
4568 };
4569
4570 return ZipObservable;
4571 }(ObservableBase));
4572
4573 var ZipObserver = (function (__super__) {
4574 inherits(ZipObserver, __super__);
4575 function ZipObserver(o, i, p, q, d) {
4576 this._o = o;
4577 this._i = i;
4578 this._p = p;
4579 this._q = q;
4580 this._d = d;
4581 __super__.call(this);
4582 }
4583
4584 function notEmpty(x) { return x.length > 0; }
4585 function shiftEach(x) { return x.shift(); }
4586 function notTheSame(i) {
4587 return function (x, j) {
4588 return j !== i;
4589 };
4590 }
4591
4592 ZipObserver.prototype.next = function (x) {
4593 this._q[this._i].push(x);
4594 if (this._q.every(notEmpty)) {
4595 var queuedValues = this._q.map(shiftEach);
4596 var res = tryCatch(this._p._cb).apply(null, queuedValues);
4597 if (res === errorObj) { return this._o.onError(res.e); }
4598 this._o.onNext(res);
4599 } else if (this._d.filter(notTheSame(this._i)).every(identity)) {
4600 this._o.onCompleted();
4601 }
4602 };
4603
4604 ZipObserver.prototype.error = function (e) {
4605 this._o.onError(e);
4606 };
4607
4608 ZipObserver.prototype.completed = function () {
4609 this._d[this._i] = true;
4610 this._d.every(identity) && this._o.onCompleted();
4611 };
4612
4613 return ZipObserver;
4614 }(AbstractObserver));
4615
4616 /**
4617 * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
4618 * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
4619 * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
4620 */
4621 observableProto.zip = function () {
4622 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4623
4624 var len = arguments.length, args = new Array(len);
4625 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4626 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4627 Array.isArray(args[0]) && (args = args[0]);
4628
4629 var parent = this;
4630 args.unshift(parent);
4631
4632 return new ZipObservable(args, resultSelector);
4633 };
4634
4635 /**
4636 * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
4637 * @param arguments Observable sources.
4638 * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
4639 * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
4640 */
4641 Observable.zip = function () {
4642 var len = arguments.length, args = new Array(len);
4643 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4644 if (Array.isArray(args[0])) {
4645 args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
4646 }
4647 var first = args.shift();
4648 return first.zip.apply(first, args);
4649 };
4650
4651function falseFactory() { return false; }
4652function emptyArrayFactory() { return []; }
4653function argumentsToArray() {
4654 var len = arguments.length, args = new Array(len);
4655 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4656 return args;
4657}
4658
4659var ZipIterableObservable = (function(__super__) {
4660 inherits(ZipIterableObservable, __super__);
4661 function ZipIterableObservable(sources, cb) {
4662 this.sources = sources;
4663 this._cb = cb;
4664 __super__.call(this);
4665 }
4666
4667 ZipIterableObservable.prototype.subscribeCore = function (o) {
4668 var sources = this.sources, len = sources.length, subscriptions = new Array(len);
4669
4670 var state = {
4671 q: arrayInitialize(len, emptyArrayFactory),
4672 done: arrayInitialize(len, falseFactory),
4673 cb: this._cb,
4674 o: o
4675 };
4676
4677 for (var i = 0; i < len; i++) {
4678 (function (i) {
4679 var source = sources[i], sad = new SingleAssignmentDisposable();
4680 (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
4681
4682 subscriptions[i] = sad;
4683 sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));
4684 }(i));
4685 }
4686
4687 return new NAryDisposable(subscriptions);
4688 };
4689
4690 return ZipIterableObservable;
4691}(ObservableBase));
4692
4693var ZipIterableObserver = (function (__super__) {
4694 inherits(ZipIterableObserver, __super__);
4695 function ZipIterableObserver(s, i) {
4696 this._s = s;
4697 this._i = i;
4698 __super__.call(this);
4699 }
4700
4701 function notEmpty(x) { return x.length > 0; }
4702 function shiftEach(x) { return x.shift(); }
4703 function notTheSame(i) {
4704 return function (x, j) {
4705 return j !== i;
4706 };
4707 }
4708
4709 ZipIterableObserver.prototype.next = function (x) {
4710 this._s.q[this._i].push(x);
4711 if (this._s.q.every(notEmpty)) {
4712 var queuedValues = this._s.q.map(shiftEach),
4713 res = tryCatch(this._s.cb).apply(null, queuedValues);
4714 if (res === errorObj) { return this._s.o.onError(res.e); }
4715 this._s.o.onNext(res);
4716 } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {
4717 this._s.o.onCompleted();
4718 }
4719 };
4720
4721 ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };
4722
4723 ZipIterableObserver.prototype.completed = function () {
4724 this._s.done[this._i] = true;
4725 this._s.done.every(identity) && this._s.o.onCompleted();
4726 };
4727
4728 return ZipIterableObserver;
4729}(AbstractObserver));
4730
4731/**
4732 * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
4733 * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
4734 * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
4735 */
4736observableProto.zipIterable = function () {
4737 if (arguments.length === 0) { throw new Error('invalid arguments'); }
4738
4739 var len = arguments.length, args = new Array(len);
4740 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
4741 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
4742
4743 var parent = this;
4744 args.unshift(parent);
4745 return new ZipIterableObservable(args, resultSelector);
4746};
4747
4748 function asObservable(source) {
4749 return function subscribe(o) { return source.subscribe(o); };
4750 }
4751
4752 /**
4753 * Hides the identity of an observable sequence.
4754 * @returns {Observable} An observable sequence that hides the identity of the source sequence.
4755 */
4756 observableProto.asObservable = function () {
4757 return new AnonymousObservable(asObservable(this), this);
4758 };
4759
4760 function toArray(x) { return x.toArray(); }
4761 function notEmpty(x) { return x.length > 0; }
4762
4763 /**
4764 * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
4765 * @param {Number} count Length of each buffer.
4766 * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
4767 * @returns {Observable} An observable sequence of buffers.
4768 */
4769 observableProto.bufferWithCount = function (count, skip) {
4770 typeof skip !== 'number' && (skip = count);
4771 return this.windowWithCount(count, skip)
4772 .flatMap(toArray)
4773 .filter(notEmpty);
4774 };
4775
4776 var DematerializeObservable = (function (__super__) {
4777 inherits(DematerializeObservable, __super__);
4778 function DematerializeObservable(source) {
4779 this.source = source;
4780 __super__.call(this);
4781 }
4782
4783 DematerializeObservable.prototype.subscribeCore = function (o) {
4784 return this.source.subscribe(new DematerializeObserver(o));
4785 };
4786
4787 return DematerializeObservable;
4788 }(ObservableBase));
4789
4790 var DematerializeObserver = (function (__super__) {
4791 inherits(DematerializeObserver, __super__);
4792
4793 function DematerializeObserver(o) {
4794 this._o = o;
4795 __super__.call(this);
4796 }
4797
4798 DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };
4799 DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };
4800 DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };
4801
4802 return DematerializeObserver;
4803 }(AbstractObserver));
4804
4805 /**
4806 * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
4807 * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
4808 */
4809 observableProto.dematerialize = function () {
4810 return new DematerializeObservable(this);
4811 };
4812
4813 var DistinctUntilChangedObservable = (function(__super__) {
4814 inherits(DistinctUntilChangedObservable, __super__);
4815 function DistinctUntilChangedObservable(source, keyFn, comparer) {
4816 this.source = source;
4817 this.keyFn = keyFn;
4818 this.comparer = comparer;
4819 __super__.call(this);
4820 }
4821
4822 DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
4823 return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
4824 };
4825
4826 return DistinctUntilChangedObservable;
4827 }(ObservableBase));
4828
4829 var DistinctUntilChangedObserver = (function(__super__) {
4830 inherits(DistinctUntilChangedObserver, __super__);
4831 function DistinctUntilChangedObserver(o, keyFn, comparer) {
4832 this.o = o;
4833 this.keyFn = keyFn;
4834 this.comparer = comparer;
4835 this.hasCurrentKey = false;
4836 this.currentKey = null;
4837 __super__.call(this);
4838 }
4839
4840 DistinctUntilChangedObserver.prototype.next = function (x) {
4841 var key = x, comparerEquals;
4842 if (isFunction(this.keyFn)) {
4843 key = tryCatch(this.keyFn)(x);
4844 if (key === errorObj) { return this.o.onError(key.e); }
4845 }
4846 if (this.hasCurrentKey) {
4847 comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
4848 if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
4849 }
4850 if (!this.hasCurrentKey || !comparerEquals) {
4851 this.hasCurrentKey = true;
4852 this.currentKey = key;
4853 this.o.onNext(x);
4854 }
4855 };
4856 DistinctUntilChangedObserver.prototype.error = function(e) {
4857 this.o.onError(e);
4858 };
4859 DistinctUntilChangedObserver.prototype.completed = function () {
4860 this.o.onCompleted();
4861 };
4862
4863 return DistinctUntilChangedObserver;
4864 }(AbstractObserver));
4865
4866 /**
4867 * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
4868 * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
4869 * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
4870 * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
4871 */
4872 observableProto.distinctUntilChanged = function (keyFn, comparer) {
4873 comparer || (comparer = defaultComparer);
4874 return new DistinctUntilChangedObservable(this, keyFn, comparer);
4875 };
4876
4877 var TapObservable = (function(__super__) {
4878 inherits(TapObservable,__super__);
4879 function TapObservable(source, observerOrOnNext, onError, onCompleted) {
4880 this.source = source;
4881 this._oN = observerOrOnNext;
4882 this._oE = onError;
4883 this._oC = onCompleted;
4884 __super__.call(this);
4885 }
4886
4887 TapObservable.prototype.subscribeCore = function(o) {
4888 return this.source.subscribe(new InnerObserver(o, this));
4889 };
4890
4891 inherits(InnerObserver, AbstractObserver);
4892 function InnerObserver(o, p) {
4893 this.o = o;
4894 this.t = !p._oN || isFunction(p._oN) ?
4895 observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
4896 p._oN;
4897 this.isStopped = false;
4898 AbstractObserver.call(this);
4899 }
4900 InnerObserver.prototype.next = function(x) {
4901 var res = tryCatch(this.t.onNext).call(this.t, x);
4902 if (res === errorObj) { this.o.onError(res.e); }
4903 this.o.onNext(x);
4904 };
4905 InnerObserver.prototype.error = function(err) {
4906 var res = tryCatch(this.t.onError).call(this.t, err);
4907 if (res === errorObj) { return this.o.onError(res.e); }
4908 this.o.onError(err);
4909 };
4910 InnerObserver.prototype.completed = function() {
4911 var res = tryCatch(this.t.onCompleted).call(this.t);
4912 if (res === errorObj) { return this.o.onError(res.e); }
4913 this.o.onCompleted();
4914 };
4915
4916 return TapObservable;
4917 }(ObservableBase));
4918
4919 /**
4920 * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
4921 * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
4922 * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
4923 * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
4924 * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
4925 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4926 */
4927 observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
4928 return new TapObservable(this, observerOrOnNext, onError, onCompleted);
4929 };
4930
4931 /**
4932 * Invokes an action for each element in the observable sequence.
4933 * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
4934 * @param {Function} onNext Action to invoke for each element in the observable sequence.
4935 * @param {Any} [thisArg] Object to use as this when executing callback.
4936 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4937 */
4938 observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
4939 return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
4940 };
4941
4942 /**
4943 * Invokes an action upon exceptional termination of the observable sequence.
4944 * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
4945 * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
4946 * @param {Any} [thisArg] Object to use as this when executing callback.
4947 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4948 */
4949 observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
4950 return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
4951 };
4952
4953 /**
4954 * Invokes an action upon graceful termination of the observable sequence.
4955 * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
4956 * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
4957 * @param {Any} [thisArg] Object to use as this when executing callback.
4958 * @returns {Observable} The source sequence with the side-effecting behavior applied.
4959 */
4960 observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
4961 return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
4962 };
4963
4964 var FinallyObservable = (function (__super__) {
4965 inherits(FinallyObservable, __super__);
4966 function FinallyObservable(source, fn, thisArg) {
4967 this.source = source;
4968 this._fn = bindCallback(fn, thisArg, 0);
4969 __super__.call(this);
4970 }
4971
4972 FinallyObservable.prototype.subscribeCore = function (o) {
4973 var d = tryCatch(this.source.subscribe).call(this.source, o);
4974 if (d === errorObj) {
4975 this._fn();
4976 thrower(d.e);
4977 }
4978
4979 return new FinallyDisposable(d, this._fn);
4980 };
4981
4982 function FinallyDisposable(s, fn) {
4983 this.isDisposed = false;
4984 this._s = s;
4985 this._fn = fn;
4986 }
4987 FinallyDisposable.prototype.dispose = function () {
4988 if (!this.isDisposed) {
4989 var res = tryCatch(this._s.dispose).call(this._s);
4990 this._fn();
4991 res === errorObj && thrower(res.e);
4992 }
4993 };
4994
4995 return FinallyObservable;
4996
4997 }(ObservableBase));
4998
4999 /**
5000 * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
5001 * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
5002 * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
5003 */
5004 observableProto['finally'] = function (action, thisArg) {
5005 return new FinallyObservable(this, action, thisArg);
5006 };
5007
5008 var IgnoreElementsObservable = (function(__super__) {
5009 inherits(IgnoreElementsObservable, __super__);
5010
5011 function IgnoreElementsObservable(source) {
5012 this.source = source;
5013 __super__.call(this);
5014 }
5015
5016 IgnoreElementsObservable.prototype.subscribeCore = function (o) {
5017 return this.source.subscribe(new InnerObserver(o));
5018 };
5019
5020 function InnerObserver(o) {
5021 this.o = o;
5022 this.isStopped = false;
5023 }
5024 InnerObserver.prototype.onNext = noop;
5025 InnerObserver.prototype.onError = function (err) {
5026 if(!this.isStopped) {
5027 this.isStopped = true;
5028 this.o.onError(err);
5029 }
5030 };
5031 InnerObserver.prototype.onCompleted = function () {
5032 if(!this.isStopped) {
5033 this.isStopped = true;
5034 this.o.onCompleted();
5035 }
5036 };
5037 InnerObserver.prototype.dispose = function() { this.isStopped = true; };
5038 InnerObserver.prototype.fail = function (e) {
5039 if (!this.isStopped) {
5040 this.isStopped = true;
5041 this.observer.onError(e);
5042 return true;
5043 }
5044
5045 return false;
5046 };
5047
5048 return IgnoreElementsObservable;
5049 }(ObservableBase));
5050
5051 /**
5052 * Ignores all elements in an observable sequence leaving only the termination messages.
5053 * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
5054 */
5055 observableProto.ignoreElements = function () {
5056 return new IgnoreElementsObservable(this);
5057 };
5058
5059 var MaterializeObservable = (function (__super__) {
5060 inherits(MaterializeObservable, __super__);
5061 function MaterializeObservable(source, fn) {
5062 this.source = source;
5063 __super__.call(this);
5064 }
5065
5066 MaterializeObservable.prototype.subscribeCore = function (o) {
5067 return this.source.subscribe(new MaterializeObserver(o));
5068 };
5069
5070 return MaterializeObservable;
5071 }(ObservableBase));
5072
5073 var MaterializeObserver = (function (__super__) {
5074 inherits(MaterializeObserver, __super__);
5075
5076 function MaterializeObserver(o) {
5077 this._o = o;
5078 __super__.call(this);
5079 }
5080
5081 MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };
5082 MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };
5083 MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };
5084
5085 return MaterializeObserver;
5086 }(AbstractObserver));
5087
5088 /**
5089 * Materializes the implicit notifications of an observable sequence as explicit notification values.
5090 * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
5091 */
5092 observableProto.materialize = function () {
5093 return new MaterializeObservable(this);
5094 };
5095
5096 /**
5097 * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
5098 * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
5099 * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
5100 */
5101 observableProto.repeat = function (repeatCount) {
5102 return enumerableRepeat(this, repeatCount).concat();
5103 };
5104
5105 /**
5106 * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
5107 * Note if you encounter an error and want it to retry once, then you must use .retry(2);
5108 *
5109 * @example
5110 * var res = retried = retry.repeat();
5111 * var res = retried = retry.repeat(2);
5112 * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
5113 * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
5114 */
5115 observableProto.retry = function (retryCount) {
5116 return enumerableRepeat(this, retryCount).catchError();
5117 };
5118
5119 /**
5120 * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
5121 * if the notifier completes, the observable sequence completes.
5122 *
5123 * @example
5124 * var timer = Observable.timer(500);
5125 * var source = observable.retryWhen(timer);
5126 * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
5127 * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
5128 */
5129 observableProto.retryWhen = function (notifier) {
5130 return enumerableRepeat(this).catchErrorWhen(notifier);
5131 };
5132 var ScanObservable = (function(__super__) {
5133 inherits(ScanObservable, __super__);
5134 function ScanObservable(source, accumulator, hasSeed, seed) {
5135 this.source = source;
5136 this.accumulator = accumulator;
5137 this.hasSeed = hasSeed;
5138 this.seed = seed;
5139 __super__.call(this);
5140 }
5141
5142 ScanObservable.prototype.subscribeCore = function(o) {
5143 return this.source.subscribe(new ScanObserver(o,this));
5144 };
5145
5146 return ScanObservable;
5147 }(ObservableBase));
5148
5149 var ScanObserver = (function (__super__) {
5150 inherits(ScanObserver, __super__);
5151 function ScanObserver(o, parent) {
5152 this._o = o;
5153 this._p = parent;
5154 this._fn = parent.accumulator;
5155 this._hs = parent.hasSeed;
5156 this._s = parent.seed;
5157 this._ha = false;
5158 this._a = null;
5159 this._hv = false;
5160 this._i = 0;
5161 __super__.call(this);
5162 }
5163
5164 ScanObserver.prototype.next = function (x) {
5165 !this._hv && (this._hv = true);
5166 if (this._ha) {
5167 this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
5168 } else {
5169 this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
5170 this._ha = true;
5171 }
5172 if (this._a === errorObj) { return this._o.onError(this._a.e); }
5173 this._o.onNext(this._a);
5174 this._i++;
5175 };
5176
5177 ScanObserver.prototype.error = function (e) {
5178 this._o.onError(e);
5179 };
5180
5181 ScanObserver.prototype.completed = function () {
5182 !this._hv && this._hs && this._o.onNext(this._s);
5183 this._o.onCompleted();
5184 };
5185
5186 return ScanObserver;
5187 }(AbstractObserver));
5188
5189 /**
5190 * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
5191 * For aggregation behavior with no intermediate results, see Observable.aggregate.
5192 * @param {Mixed} [seed] The initial accumulator value.
5193 * @param {Function} accumulator An accumulator function to be invoked on each element.
5194 * @returns {Observable} An observable sequence containing the accumulated values.
5195 */
5196 observableProto.scan = function () {
5197 var hasSeed = false, seed, accumulator = arguments[0];
5198 if (arguments.length === 2) {
5199 hasSeed = true;
5200 seed = arguments[1];
5201 }
5202 return new ScanObservable(this, accumulator, hasSeed, seed);
5203 };
5204
5205 var SkipLastObservable = (function (__super__) {
5206 inherits(SkipLastObservable, __super__);
5207 function SkipLastObservable(source, c) {
5208 this.source = source;
5209 this._c = c;
5210 __super__.call(this);
5211 }
5212
5213 SkipLastObservable.prototype.subscribeCore = function (o) {
5214 return this.source.subscribe(new SkipLastObserver(o, this._c));
5215 };
5216
5217 return SkipLastObservable;
5218 }(ObservableBase));
5219
5220 var SkipLastObserver = (function (__super__) {
5221 inherits(SkipLastObserver, __super__);
5222 function SkipLastObserver(o, c) {
5223 this._o = o;
5224 this._c = c;
5225 this._q = [];
5226 __super__.call(this);
5227 }
5228
5229 SkipLastObserver.prototype.next = function (x) {
5230 this._q.push(x);
5231 this._q.length > this._c && this._o.onNext(this._q.shift());
5232 };
5233
5234 SkipLastObserver.prototype.error = function (e) {
5235 this._o.onError(e);
5236 };
5237
5238 SkipLastObserver.prototype.completed = function () {
5239 this._o.onCompleted();
5240 };
5241
5242 return SkipLastObserver;
5243 }(AbstractObserver));
5244
5245 /**
5246 * Bypasses a specified number of elements at the end of an observable sequence.
5247 * @description
5248 * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
5249 * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
5250 * @param count Number of elements to bypass at the end of the source sequence.
5251 * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
5252 */
5253 observableProto.skipLast = function (count) {
5254 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5255 return new SkipLastObservable(this, count);
5256 };
5257
5258 /**
5259 * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
5260 * @example
5261 * var res = source.startWith(1, 2, 3);
5262 * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
5263 * @param {Arguments} args The specified values to prepend to the observable sequence
5264 * @returns {Observable} The source sequence prepended with the specified values.
5265 */
5266 observableProto.startWith = function () {
5267 var values, scheduler, start = 0;
5268 if (!!arguments.length && isScheduler(arguments[0])) {
5269 scheduler = arguments[0];
5270 start = 1;
5271 } else {
5272 scheduler = immediateScheduler;
5273 }
5274 for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
5275 return enumerableOf([observableFromArray(args, scheduler), this]).concat();
5276 };
5277
5278 var TakeLastObserver = (function (__super__) {
5279 inherits(TakeLastObserver, __super__);
5280 function TakeLastObserver(o, c) {
5281 this._o = o;
5282 this._c = c;
5283 this._q = [];
5284 __super__.call(this);
5285 }
5286
5287 TakeLastObserver.prototype.next = function (x) {
5288 this._q.push(x);
5289 this._q.length > this._c && this._q.shift();
5290 };
5291
5292 TakeLastObserver.prototype.error = function (e) {
5293 this._o.onError(e);
5294 };
5295
5296 TakeLastObserver.prototype.completed = function () {
5297 while (this._q.length > 0) { this._o.onNext(this._q.shift()); }
5298 this._o.onCompleted();
5299 };
5300
5301 return TakeLastObserver;
5302 }(AbstractObserver));
5303
5304 /**
5305 * Returns a specified number of contiguous elements from the end of an observable sequence.
5306 * @description
5307 * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
5308 * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
5309 * @param {Number} count Number of elements to take from the end of the source sequence.
5310 * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
5311 */
5312 observableProto.takeLast = function (count) {
5313 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5314 var source = this;
5315 return new AnonymousObservable(function (o) {
5316 return source.subscribe(new TakeLastObserver(o, count));
5317 }, source);
5318 };
5319
5320 var TakeLastBufferObserver = (function (__super__) {
5321 inherits(TakeLastBufferObserver, __super__);
5322 function TakeLastBufferObserver(o, c) {
5323 this._o = o;
5324 this._c = c;
5325 this._q = [];
5326 __super__.call(this);
5327 }
5328
5329 TakeLastBufferObserver.prototype.next = function (x) {
5330 this._q.push(x);
5331 this._q.length > this._c && this._q.shift();
5332 };
5333
5334 TakeLastBufferObserver.prototype.error = function (e) {
5335 this._o.onError(e);
5336 };
5337
5338 TakeLastBufferObserver.prototype.completed = function () {
5339 this._o.onNext(this._q);
5340 this._o.onCompleted();
5341 };
5342
5343 return TakeLastBufferObserver;
5344 }(AbstractObserver));
5345
5346 /**
5347 * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
5348 *
5349 * @description
5350 * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
5351 * source sequence, this buffer is produced on the result sequence.
5352 * @param {Number} count Number of elements to take from the end of the source sequence.
5353 * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
5354 */
5355 observableProto.takeLastBuffer = function (count) {
5356 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5357 var source = this;
5358 return new AnonymousObservable(function (o) {
5359 return source.subscribe(new TakeLastBufferObserver(o, count));
5360 }, source);
5361 };
5362
5363 /**
5364 * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
5365 * @param {Number} count Length of each window.
5366 * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
5367 * @returns {Observable} An observable sequence of windows.
5368 */
5369 observableProto.windowWithCount = function (count, skip) {
5370 var source = this;
5371 +count || (count = 0);
5372 Math.abs(count) === Infinity && (count = 0);
5373 if (count <= 0) { throw new ArgumentOutOfRangeError(); }
5374 skip == null && (skip = count);
5375 +skip || (skip = 0);
5376 Math.abs(skip) === Infinity && (skip = 0);
5377
5378 if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
5379 return new AnonymousObservable(function (observer) {
5380 var m = new SingleAssignmentDisposable(),
5381 refCountDisposable = new RefCountDisposable(m),
5382 n = 0,
5383 q = [];
5384
5385 function createWindow () {
5386 var s = new Subject();
5387 q.push(s);
5388 observer.onNext(addRef(s, refCountDisposable));
5389 }
5390
5391 createWindow();
5392
5393 m.setDisposable(source.subscribe(
5394 function (x) {
5395 for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
5396 var c = n - count + 1;
5397 c >= 0 && c % skip === 0 && q.shift().onCompleted();
5398 ++n % skip === 0 && createWindow();
5399 },
5400 function (e) {
5401 while (q.length > 0) { q.shift().onError(e); }
5402 observer.onError(e);
5403 },
5404 function () {
5405 while (q.length > 0) { q.shift().onCompleted(); }
5406 observer.onCompleted();
5407 }
5408 ));
5409 return refCountDisposable;
5410 }, source);
5411 };
5412
5413observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) {
5414 return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1);
5415};
5416 /**
5417 * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
5418 * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
5419 * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
5420 * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
5421 * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
5422 * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
5423 */
5424 observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
5425 var source = this,
5426 onNextFunc = bindCallback(onNext, thisArg, 2),
5427 onErrorFunc = bindCallback(onError, thisArg, 1),
5428 onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
5429 return new AnonymousObservable(function (observer) {
5430 var index = 0;
5431 return source.subscribe(
5432 function (x) {
5433 var result;
5434 try {
5435 result = onNextFunc(x, index++);
5436 } catch (e) {
5437 observer.onError(e);
5438 return;
5439 }
5440 isPromise(result) && (result = observableFromPromise(result));
5441 observer.onNext(result);
5442 },
5443 function (err) {
5444 var result;
5445 try {
5446 result = onErrorFunc(err);
5447 } catch (e) {
5448 observer.onError(e);
5449 return;
5450 }
5451 isPromise(result) && (result = observableFromPromise(result));
5452 observer.onNext(result);
5453 observer.onCompleted();
5454 },
5455 function () {
5456 var result;
5457 try {
5458 result = onCompletedFunc();
5459 } catch (e) {
5460 observer.onError(e);
5461 return;
5462 }
5463 isPromise(result) && (result = observableFromPromise(result));
5464 observer.onNext(result);
5465 observer.onCompleted();
5466 });
5467 }, this).concatAll();
5468 };
5469
5470 var DefaultIfEmptyObserver = (function (__super__) {
5471 inherits(DefaultIfEmptyObserver, __super__);
5472 function DefaultIfEmptyObserver(o, d) {
5473 this._o = o;
5474 this._d = d;
5475 this._f = false;
5476 __super__.call(this);
5477 }
5478
5479 DefaultIfEmptyObserver.prototype.next = function (x) {
5480 this._f = true;
5481 this._o.onNext(x);
5482 };
5483
5484 DefaultIfEmptyObserver.prototype.error = function (e) {
5485 this._o.onError(e);
5486 };
5487
5488 DefaultIfEmptyObserver.prototype.completed = function () {
5489 !this._f && this._o.onNext(this._d);
5490 this._o.onCompleted();
5491 };
5492
5493 return DefaultIfEmptyObserver;
5494 }(AbstractObserver));
5495
5496 /**
5497 * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
5498 *
5499 * var res = obs = xs.defaultIfEmpty();
5500 * 2 - obs = xs.defaultIfEmpty(false);
5501 *
5502 * @memberOf Observable#
5503 * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
5504 * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
5505 */
5506 observableProto.defaultIfEmpty = function (defaultValue) {
5507 var source = this;
5508 defaultValue === undefined && (defaultValue = null);
5509 return new AnonymousObservable(function (o) {
5510 return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
5511 }, source);
5512 };
5513
5514 // Swap out for Array.findIndex
5515 function arrayIndexOfComparer(array, item, comparer) {
5516 for (var i = 0, len = array.length; i < len; i++) {
5517 if (comparer(array[i], item)) { return i; }
5518 }
5519 return -1;
5520 }
5521
5522 function HashSet(comparer) {
5523 this.comparer = comparer;
5524 this.set = [];
5525 }
5526 HashSet.prototype.push = function(value) {
5527 var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
5528 retValue && this.set.push(value);
5529 return retValue;
5530 };
5531
5532 var DistinctObservable = (function (__super__) {
5533 inherits(DistinctObservable, __super__);
5534 function DistinctObservable(source, keyFn, cmpFn) {
5535 this.source = source;
5536 this._keyFn = keyFn;
5537 this._cmpFn = cmpFn;
5538 __super__.call(this);
5539 }
5540
5541 DistinctObservable.prototype.subscribeCore = function (o) {
5542 return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
5543 };
5544
5545 return DistinctObservable;
5546 }(ObservableBase));
5547
5548 var DistinctObserver = (function (__super__) {
5549 inherits(DistinctObserver, __super__);
5550 function DistinctObserver(o, keyFn, cmpFn) {
5551 this._o = o;
5552 this._keyFn = keyFn;
5553 this._h = new HashSet(cmpFn);
5554 __super__.call(this);
5555 }
5556
5557 DistinctObserver.prototype.next = function (x) {
5558 var key = x;
5559 if (isFunction(this._keyFn)) {
5560 key = tryCatch(this._keyFn)(x);
5561 if (key === errorObj) { return this._o.onError(key.e); }
5562 }
5563 this._h.push(key) && this._o.onNext(x);
5564 };
5565
5566 DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
5567 DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
5568
5569 return DistinctObserver;
5570 }(AbstractObserver));
5571
5572 /**
5573 * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
5574 * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
5575 *
5576 * @example
5577 * var res = obs = xs.distinct();
5578 * 2 - obs = xs.distinct(function (x) { return x.id; });
5579 * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
5580 * @param {Function} [keySelector] A function to compute the comparison key for each element.
5581 * @param {Function} [comparer] Used to compare items in the collection.
5582 * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
5583 */
5584 observableProto.distinct = function (keySelector, comparer) {
5585 comparer || (comparer = defaultComparer);
5586 return new DistinctObservable(this, keySelector, comparer);
5587 };
5588
5589 /**
5590 * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
5591 *
5592 * @example
5593 * var res = observable.groupBy(function (x) { return x.id; });
5594 * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
5595 * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
5596 * @param {Function} keySelector A function to extract the key for each element.
5597 * @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
5598 * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
5599 */
5600 observableProto.groupBy = function (keySelector, elementSelector) {
5601 return this.groupByUntil(keySelector, elementSelector, observableNever);
5602 };
5603
5604 /**
5605 * Groups the elements of an observable sequence according to a specified key selector function.
5606 * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
5607 * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
5608 *
5609 * @example
5610 * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
5611 * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
5612 * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
5613 * @param {Function} keySelector A function to extract the key for each element.
5614 * @param {Function} durationSelector A function to signal the expiration of a group.
5615 * @returns {Observable}
5616 * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
5617 * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
5618 *
5619 */
5620 observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) {
5621 var source = this;
5622 return new AnonymousObservable(function (o) {
5623 var map = new Map(),
5624 groupDisposable = new CompositeDisposable(),
5625 refCountDisposable = new RefCountDisposable(groupDisposable),
5626 handleError = function (e) { return function (item) { item.onError(e); }; };
5627
5628 groupDisposable.add(
5629 source.subscribe(function (x) {
5630 var key = tryCatch(keySelector)(x);
5631 if (key === errorObj) {
5632 map.forEach(handleError(key.e));
5633 return o.onError(key.e);
5634 }
5635
5636 var fireNewMapEntry = false, writer = map.get(key);
5637 if (writer === undefined) {
5638 writer = new Subject();
5639 map.set(key, writer);
5640 fireNewMapEntry = true;
5641 }
5642
5643 if (fireNewMapEntry) {
5644 var group = new GroupedObservable(key, writer, refCountDisposable),
5645 durationGroup = new GroupedObservable(key, writer);
5646 var duration = tryCatch(durationSelector)(durationGroup);
5647 if (duration === errorObj) {
5648 map.forEach(handleError(duration.e));
5649 return o.onError(duration.e);
5650 }
5651
5652 o.onNext(group);
5653
5654 var md = new SingleAssignmentDisposable();
5655 groupDisposable.add(md);
5656
5657 md.setDisposable(duration.take(1).subscribe(
5658 noop,
5659 function (e) {
5660 map.forEach(handleError(e));
5661 o.onError(e);
5662 },
5663 function () {
5664 if (map['delete'](key)) { writer.onCompleted(); }
5665 groupDisposable.remove(md);
5666 }));
5667 }
5668
5669 var element = x;
5670 if (isFunction(elementSelector)) {
5671 element = tryCatch(elementSelector)(x);
5672 if (element === errorObj) {
5673 map.forEach(handleError(element.e));
5674 return o.onError(element.e);
5675 }
5676 }
5677
5678 writer.onNext(element);
5679 }, function (e) {
5680 map.forEach(handleError(e));
5681 o.onError(e);
5682 }, function () {
5683 map.forEach(function (item) { item.onCompleted(); });
5684 o.onCompleted();
5685 }));
5686
5687 return refCountDisposable;
5688 }, source);
5689 };
5690
5691 var MapObservable = (function (__super__) {
5692 inherits(MapObservable, __super__);
5693
5694 function MapObservable(source, selector, thisArg) {
5695 this.source = source;
5696 this.selector = bindCallback(selector, thisArg, 3);
5697 __super__.call(this);
5698 }
5699
5700 function innerMap(selector, self) {
5701 return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };
5702 }
5703
5704 MapObservable.prototype.internalMap = function (selector, thisArg) {
5705 return new MapObservable(this.source, innerMap(selector, this), thisArg);
5706 };
5707
5708 MapObservable.prototype.subscribeCore = function (o) {
5709 return this.source.subscribe(new InnerObserver(o, this.selector, this));
5710 };
5711
5712 inherits(InnerObserver, AbstractObserver);
5713 function InnerObserver(o, selector, source) {
5714 this.o = o;
5715 this.selector = selector;
5716 this.source = source;
5717 this.i = 0;
5718 AbstractObserver.call(this);
5719 }
5720
5721 InnerObserver.prototype.next = function(x) {
5722 var result = tryCatch(this.selector)(x, this.i++, this.source);
5723 if (result === errorObj) { return this.o.onError(result.e); }
5724 this.o.onNext(result);
5725 };
5726
5727 InnerObserver.prototype.error = function (e) {
5728 this.o.onError(e);
5729 };
5730
5731 InnerObserver.prototype.completed = function () {
5732 this.o.onCompleted();
5733 };
5734
5735 return MapObservable;
5736
5737 }(ObservableBase));
5738
5739 /**
5740 * Projects each element of an observable sequence into a new form by incorporating the element's index.
5741 * @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.
5742 * @param {Any} [thisArg] Object to use as this when executing callback.
5743 * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
5744 */
5745 observableProto.map = observableProto.select = function (selector, thisArg) {
5746 var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
5747 return this instanceof MapObservable ?
5748 this.internalMap(selectorFn, thisArg) :
5749 new MapObservable(this, selectorFn, thisArg);
5750 };
5751
5752 function plucker(args, len) {
5753 return function mapper(x) {
5754 var currentProp = x;
5755 for (var i = 0; i < len; i++) {
5756 var p = currentProp[args[i]];
5757 if (typeof p !== 'undefined') {
5758 currentProp = p;
5759 } else {
5760 return undefined;
5761 }
5762 }
5763 return currentProp;
5764 }
5765 }
5766
5767 /**
5768 * Retrieves the value of a specified nested property from all elements in
5769 * the Observable sequence.
5770 * @param {Arguments} arguments The nested properties to pluck.
5771 * @returns {Observable} Returns a new Observable sequence of property values.
5772 */
5773 observableProto.pluck = function () {
5774 var len = arguments.length, args = new Array(len);
5775 if (len === 0) { throw new Error('List of properties cannot be empty.'); }
5776 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
5777 return this.map(plucker(args, len));
5778 };
5779
5780observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) {
5781 return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
5782};
5783
5784 /**
5785 * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
5786 * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
5787 * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
5788 * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
5789 * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
5790 * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
5791 */
5792 observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
5793 var source = this;
5794 return new AnonymousObservable(function (observer) {
5795 var index = 0;
5796
5797 return source.subscribe(
5798 function (x) {
5799 var result;
5800 try {
5801 result = onNext.call(thisArg, x, index++);
5802 } catch (e) {
5803 observer.onError(e);
5804 return;
5805 }
5806 isPromise(result) && (result = observableFromPromise(result));
5807 observer.onNext(result);
5808 },
5809 function (err) {
5810 var result;
5811 try {
5812 result = onError.call(thisArg, err);
5813 } catch (e) {
5814 observer.onError(e);
5815 return;
5816 }
5817 isPromise(result) && (result = observableFromPromise(result));
5818 observer.onNext(result);
5819 observer.onCompleted();
5820 },
5821 function () {
5822 var result;
5823 try {
5824 result = onCompleted.call(thisArg);
5825 } catch (e) {
5826 observer.onError(e);
5827 return;
5828 }
5829 isPromise(result) && (result = observableFromPromise(result));
5830 observer.onNext(result);
5831 observer.onCompleted();
5832 });
5833 }, source).mergeAll();
5834 };
5835
5836Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) {
5837 return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
5838};
5839 var SkipObservable = (function(__super__) {
5840 inherits(SkipObservable, __super__);
5841 function SkipObservable(source, count) {
5842 this.source = source;
5843 this._count = count;
5844 __super__.call(this);
5845 }
5846
5847 SkipObservable.prototype.subscribeCore = function (o) {
5848 return this.source.subscribe(new SkipObserver(o, this._count));
5849 };
5850
5851 function SkipObserver(o, c) {
5852 this._o = o;
5853 this._r = c;
5854 AbstractObserver.call(this);
5855 }
5856
5857 inherits(SkipObserver, AbstractObserver);
5858
5859 SkipObserver.prototype.next = function (x) {
5860 if (this._r <= 0) {
5861 this._o.onNext(x);
5862 } else {
5863 this._r--;
5864 }
5865 };
5866 SkipObserver.prototype.error = function(e) { this._o.onError(e); };
5867 SkipObserver.prototype.completed = function() { this._o.onCompleted(); };
5868
5869 return SkipObservable;
5870 }(ObservableBase));
5871
5872 /**
5873 * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
5874 * @param {Number} count The number of elements to skip before returning the remaining elements.
5875 * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
5876 */
5877 observableProto.skip = function (count) {
5878 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5879 return new SkipObservable(this, count);
5880 };
5881
5882 var SkipWhileObservable = (function (__super__) {
5883 inherits(SkipWhileObservable, __super__);
5884 function SkipWhileObservable(source, fn) {
5885 this.source = source;
5886 this._fn = fn;
5887 __super__.call(this);
5888 }
5889
5890 SkipWhileObservable.prototype.subscribeCore = function (o) {
5891 return this.source.subscribe(new SkipWhileObserver(o, this));
5892 };
5893
5894 return SkipWhileObservable;
5895 }(ObservableBase));
5896
5897 var SkipWhileObserver = (function (__super__) {
5898 inherits(SkipWhileObserver, __super__);
5899
5900 function SkipWhileObserver(o, p) {
5901 this._o = o;
5902 this._p = p;
5903 this._i = 0;
5904 this._r = false;
5905 __super__.call(this);
5906 }
5907
5908 SkipWhileObserver.prototype.next = function (x) {
5909 if (!this._r) {
5910 var res = tryCatch(this._p._fn)(x, this._i++, this._p);
5911 if (res === errorObj) { return this._o.onError(res.e); }
5912 this._r = !res;
5913 }
5914 this._r && this._o.onNext(x);
5915 };
5916 SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };
5917 SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
5918
5919 return SkipWhileObserver;
5920 }(AbstractObserver));
5921
5922 /**
5923 * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
5924 * The element's index is used in the logic of the predicate function.
5925 *
5926 * var res = source.skipWhile(function (value) { return value < 10; });
5927 * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
5928 * @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.
5929 * @param {Any} [thisArg] Object to use as this when executing callback.
5930 * @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.
5931 */
5932 observableProto.skipWhile = function (predicate, thisArg) {
5933 var fn = bindCallback(predicate, thisArg, 3);
5934 return new SkipWhileObservable(this, fn);
5935 };
5936
5937 var TakeObservable = (function(__super__) {
5938 inherits(TakeObservable, __super__);
5939 function TakeObservable(source, count) {
5940 this.source = source;
5941 this._count = count;
5942 __super__.call(this);
5943 }
5944
5945 TakeObservable.prototype.subscribeCore = function (o) {
5946 return this.source.subscribe(new TakeObserver(o, this._count));
5947 };
5948
5949 function TakeObserver(o, c) {
5950 this._o = o;
5951 this._c = c;
5952 this._r = c;
5953 AbstractObserver.call(this);
5954 }
5955
5956 inherits(TakeObserver, AbstractObserver);
5957
5958 TakeObserver.prototype.next = function (x) {
5959 if (this._r-- > 0) {
5960 this._o.onNext(x);
5961 this._r <= 0 && this._o.onCompleted();
5962 }
5963 };
5964
5965 TakeObserver.prototype.error = function (e) { this._o.onError(e); };
5966 TakeObserver.prototype.completed = function () { this._o.onCompleted(); };
5967
5968 return TakeObservable;
5969 }(ObservableBase));
5970
5971 /**
5972 * 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).
5973 * @param {Number} count The number of elements to return.
5974 * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
5975 * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
5976 */
5977 observableProto.take = function (count, scheduler) {
5978 if (count < 0) { throw new ArgumentOutOfRangeError(); }
5979 if (count === 0) { return observableEmpty(scheduler); }
5980 return new TakeObservable(this, count);
5981 };
5982
5983 var TakeWhileObservable = (function (__super__) {
5984 inherits(TakeWhileObservable, __super__);
5985 function TakeWhileObservable(source, fn) {
5986 this.source = source;
5987 this._fn = fn;
5988 __super__.call(this);
5989 }
5990
5991 TakeWhileObservable.prototype.subscribeCore = function (o) {
5992 return this.source.subscribe(new TakeWhileObserver(o, this));
5993 };
5994
5995 return TakeWhileObservable;
5996 }(ObservableBase));
5997
5998 var TakeWhileObserver = (function (__super__) {
5999 inherits(TakeWhileObserver, __super__);
6000
6001 function TakeWhileObserver(o, p) {
6002 this._o = o;
6003 this._p = p;
6004 this._i = 0;
6005 this._r = true;
6006 __super__.call(this);
6007 }
6008
6009 TakeWhileObserver.prototype.next = function (x) {
6010 if (this._r) {
6011 this._r = tryCatch(this._p._fn)(x, this._i++, this._p);
6012 if (this._r === errorObj) { return this._o.onError(this._r.e); }
6013 }
6014 if (this._r) {
6015 this._o.onNext(x);
6016 } else {
6017 this._o.onCompleted();
6018 }
6019 };
6020 TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };
6021 TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
6022
6023 return TakeWhileObserver;
6024 }(AbstractObserver));
6025
6026 /**
6027 * Returns elements from an observable sequence as long as a specified condition is true.
6028 * The element's index is used in the logic of the predicate function.
6029 * @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.
6030 * @param {Any} [thisArg] Object to use as this when executing callback.
6031 * @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.
6032 */
6033 observableProto.takeWhile = function (predicate, thisArg) {
6034 var fn = bindCallback(predicate, thisArg, 3);
6035 return new TakeWhileObservable(this, fn);
6036 };
6037
6038 var FilterObservable = (function (__super__) {
6039 inherits(FilterObservable, __super__);
6040
6041 function FilterObservable(source, predicate, thisArg) {
6042 this.source = source;
6043 this.predicate = bindCallback(predicate, thisArg, 3);
6044 __super__.call(this);
6045 }
6046
6047 FilterObservable.prototype.subscribeCore = function (o) {
6048 return this.source.subscribe(new InnerObserver(o, this.predicate, this));
6049 };
6050
6051 function innerPredicate(predicate, self) {
6052 return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
6053 }
6054
6055 FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
6056 return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
6057 };
6058
6059 inherits(InnerObserver, AbstractObserver);
6060 function InnerObserver(o, predicate, source) {
6061 this.o = o;
6062 this.predicate = predicate;
6063 this.source = source;
6064 this.i = 0;
6065 AbstractObserver.call(this);
6066 }
6067
6068 InnerObserver.prototype.next = function(x) {
6069 var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
6070 if (shouldYield === errorObj) {
6071 return this.o.onError(shouldYield.e);
6072 }
6073 shouldYield && this.o.onNext(x);
6074 };
6075
6076 InnerObserver.prototype.error = function (e) {
6077 this.o.onError(e);
6078 };
6079
6080 InnerObserver.prototype.completed = function () {
6081 this.o.onCompleted();
6082 };
6083
6084 return FilterObservable;
6085
6086 }(ObservableBase));
6087
6088 /**
6089 * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
6090 * @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.
6091 * @param {Any} [thisArg] Object to use as this when executing callback.
6092 * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
6093 */
6094 observableProto.filter = observableProto.where = function (predicate, thisArg) {
6095 return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
6096 new FilterObservable(this, predicate, thisArg);
6097 };
6098
6099 var ExtremaByObservable = (function (__super__) {
6100 inherits(ExtremaByObservable, __super__);
6101 function ExtremaByObservable(source, k, c) {
6102 this.source = source;
6103 this._k = k;
6104 this._c = c;
6105 __super__.call(this);
6106 }
6107
6108 ExtremaByObservable.prototype.subscribeCore = function (o) {
6109 return this.source.subscribe(new ExtremaByObserver(o, this._k, this._c));
6110 };
6111
6112 return ExtremaByObservable;
6113 }(ObservableBase));
6114
6115 var ExtremaByObserver = (function (__super__) {
6116 inherits(ExtremaByObserver, __super__);
6117 function ExtremaByObserver(o, k, c) {
6118 this._o = o;
6119 this._k = k;
6120 this._c = c;
6121 this._v = null;
6122 this._hv = false;
6123 this._l = [];
6124 __super__.call(this);
6125 }
6126
6127 ExtremaByObserver.prototype.next = function (x) {
6128 var key = tryCatch(this._k)(x);
6129 if (key === errorObj) { return this._o.onError(key.e); }
6130 var comparison = 0;
6131 if (!this._hv) {
6132 this._hv = true;
6133 this._v = key;
6134 } else {
6135 comparison = tryCatch(this._c)(key, this._v);
6136 if (comparison === errorObj) { return this._o.onError(comparison.e); }
6137 }
6138 if (comparison > 0) {
6139 this._v = key;
6140 this._l = [];
6141 }
6142 if (comparison >= 0) { this._l.push(x); }
6143 };
6144
6145 ExtremaByObserver.prototype.error = function (e) {
6146 this._o.onError(e);
6147 };
6148
6149 ExtremaByObserver.prototype.completed = function () {
6150 this._o.onNext(this._l);
6151 this._o.onCompleted();
6152 };
6153
6154 return ExtremaByObserver;
6155 }(AbstractObserver));
6156
6157 function firstOnly(x) {
6158 if (x.length === 0) { throw new EmptyError(); }
6159 return x[0];
6160 }
6161
6162 var ReduceObservable = (function(__super__) {
6163 inherits(ReduceObservable, __super__);
6164 function ReduceObservable(source, accumulator, hasSeed, seed) {
6165 this.source = source;
6166 this.accumulator = accumulator;
6167 this.hasSeed = hasSeed;
6168 this.seed = seed;
6169 __super__.call(this);
6170 }
6171
6172 ReduceObservable.prototype.subscribeCore = function(observer) {
6173 return this.source.subscribe(new ReduceObserver(observer,this));
6174 };
6175
6176 return ReduceObservable;
6177 }(ObservableBase));
6178
6179 var ReduceObserver = (function (__super__) {
6180 inherits(ReduceObserver, __super__);
6181 function ReduceObserver(o, parent) {
6182 this._o = o;
6183 this._p = parent;
6184 this._fn = parent.accumulator;
6185 this._hs = parent.hasSeed;
6186 this._s = parent.seed;
6187 this._ha = false;
6188 this._a = null;
6189 this._hv = false;
6190 this._i = 0;
6191 __super__.call(this);
6192 }
6193
6194 ReduceObserver.prototype.next = function (x) {
6195 !this._hv && (this._hv = true);
6196 if (this._ha) {
6197 this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
6198 } else {
6199 this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
6200 this._ha = true;
6201 }
6202 if (this._a === errorObj) { return this._o.onError(this._a.e); }
6203 this._i++;
6204 };
6205
6206 ReduceObserver.prototype.error = function (e) {
6207 this._o.onError(e);
6208 };
6209
6210 ReduceObserver.prototype.completed = function () {
6211 this._hv && this._o.onNext(this._a);
6212 !this._hv && this._hs && this._o.onNext(this._s);
6213 !this._hv && !this._hs && this._o.onError(new EmptyError());
6214 this._o.onCompleted();
6215 };
6216
6217 return ReduceObserver;
6218 }(AbstractObserver));
6219
6220 /**
6221 * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
6222 * For aggregation behavior with incremental intermediate results, see Observable.scan.
6223 * @param {Function} accumulator An accumulator function to be invoked on each element.
6224 * @param {Any} [seed] The initial accumulator value.
6225 * @returns {Observable} An observable sequence containing a single element with the final accumulator value.
6226 */
6227 observableProto.reduce = function () {
6228 var hasSeed = false, seed, accumulator = arguments[0];
6229 if (arguments.length === 2) {
6230 hasSeed = true;
6231 seed = arguments[1];
6232 }
6233 return new ReduceObservable(this, accumulator, hasSeed, seed);
6234 };
6235
6236 var SomeObservable = (function (__super__) {
6237 inherits(SomeObservable, __super__);
6238 function SomeObservable(source, fn) {
6239 this.source = source;
6240 this._fn = fn;
6241 __super__.call(this);
6242 }
6243
6244 SomeObservable.prototype.subscribeCore = function (o) {
6245 return this.source.subscribe(new SomeObserver(o, this._fn, this.source));
6246 };
6247
6248 return SomeObservable;
6249 }(ObservableBase));
6250
6251 var SomeObserver = (function (__super__) {
6252 inherits(SomeObserver, __super__);
6253
6254 function SomeObserver(o, fn, s) {
6255 this._o = o;
6256 this._fn = fn;
6257 this._s = s;
6258 this._i = 0;
6259 __super__.call(this);
6260 }
6261
6262 SomeObserver.prototype.next = function (x) {
6263 var result = tryCatch(this._fn)(x, this._i++, this._s);
6264 if (result === errorObj) { return this._o.onError(result.e); }
6265 if (Boolean(result)) {
6266 this._o.onNext(true);
6267 this._o.onCompleted();
6268 }
6269 };
6270 SomeObserver.prototype.error = function (e) { this._o.onError(e); };
6271 SomeObserver.prototype.completed = function () {
6272 this._o.onNext(false);
6273 this._o.onCompleted();
6274 };
6275
6276 return SomeObserver;
6277 }(AbstractObserver));
6278
6279 /**
6280 * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
6281 * @param {Function} [predicate] A function to test each element for a condition.
6282 * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
6283 */
6284 observableProto.some = function (predicate, thisArg) {
6285 var fn = bindCallback(predicate, thisArg, 3);
6286 return new SomeObservable(this, fn);
6287 };
6288
6289 var IsEmptyObservable = (function (__super__) {
6290 inherits(IsEmptyObservable, __super__);
6291 function IsEmptyObservable(source) {
6292 this.source = source;
6293 __super__.call(this);
6294 }
6295
6296 IsEmptyObservable.prototype.subscribeCore = function (o) {
6297 return this.source.subscribe(new IsEmptyObserver(o));
6298 };
6299
6300 return IsEmptyObservable;
6301 }(ObservableBase));
6302
6303 var IsEmptyObserver = (function(__super__) {
6304 inherits(IsEmptyObserver, __super__);
6305 function IsEmptyObserver(o) {
6306 this._o = o;
6307 __super__.call(this);
6308 }
6309
6310 IsEmptyObserver.prototype.next = function () {
6311 this._o.onNext(false);
6312 this._o.onCompleted();
6313 };
6314 IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); };
6315 IsEmptyObserver.prototype.completed = function () {
6316 this._o.onNext(true);
6317 this._o.onCompleted();
6318 };
6319
6320 return IsEmptyObserver;
6321 }(AbstractObserver));
6322
6323 /**
6324 * Determines whether an observable sequence is empty.
6325 * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
6326 */
6327 observableProto.isEmpty = function () {
6328 return new IsEmptyObservable(this);
6329 };
6330
6331 var EveryObservable = (function (__super__) {
6332 inherits(EveryObservable, __super__);
6333 function EveryObservable(source, fn) {
6334 this.source = source;
6335 this._fn = fn;
6336 __super__.call(this);
6337 }
6338
6339 EveryObservable.prototype.subscribeCore = function (o) {
6340 return this.source.subscribe(new EveryObserver(o, this._fn, this.source));
6341 };
6342
6343 return EveryObservable;
6344 }(ObservableBase));
6345
6346 var EveryObserver = (function (__super__) {
6347 inherits(EveryObserver, __super__);
6348
6349 function EveryObserver(o, fn, s) {
6350 this._o = o;
6351 this._fn = fn;
6352 this._s = s;
6353 this._i = 0;
6354 __super__.call(this);
6355 }
6356
6357 EveryObserver.prototype.next = function (x) {
6358 var result = tryCatch(this._fn)(x, this._i++, this._s);
6359 if (result === errorObj) { return this._o.onError(result.e); }
6360 if (!Boolean(result)) {
6361 this._o.onNext(false);
6362 this._o.onCompleted();
6363 }
6364 };
6365 EveryObserver.prototype.error = function (e) { this._o.onError(e); };
6366 EveryObserver.prototype.completed = function () {
6367 this._o.onNext(true);
6368 this._o.onCompleted();
6369 };
6370
6371 return EveryObserver;
6372 }(AbstractObserver));
6373
6374 /**
6375 * Determines whether all elements of an observable sequence satisfy a condition.
6376 * @param {Function} [predicate] A function to test each element for a condition.
6377 * @param {Any} [thisArg] Object to use as this when executing callback.
6378 * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
6379 */
6380 observableProto.every = function (predicate, thisArg) {
6381 var fn = bindCallback(predicate, thisArg, 3);
6382 return new EveryObservable(this, fn);
6383 };
6384
6385 var IncludesObservable = (function (__super__) {
6386 inherits(IncludesObservable, __super__);
6387 function IncludesObservable(source, elem, idx) {
6388 var n = +idx || 0;
6389 Math.abs(n) === Infinity && (n = 0);
6390
6391 this.source = source;
6392 this._elem = elem;
6393 this._n = n;
6394 __super__.call(this);
6395 }
6396
6397 IncludesObservable.prototype.subscribeCore = function (o) {
6398 if (this._n < 0) {
6399 o.onNext(false);
6400 o.onCompleted();
6401 return disposableEmpty;
6402 }
6403
6404 return this.source.subscribe(new IncludesObserver(o, this._elem, this._n));
6405 };
6406
6407 return IncludesObservable;
6408 }(ObservableBase));
6409
6410 var IncludesObserver = (function (__super__) {
6411 inherits(IncludesObserver, __super__);
6412 function IncludesObserver(o, elem, n) {
6413 this._o = o;
6414 this._elem = elem;
6415 this._n = n;
6416 this._i = 0;
6417 __super__.call(this);
6418 }
6419
6420 function comparer(a, b) {
6421 return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
6422 }
6423
6424 IncludesObserver.prototype.next = function (x) {
6425 if (this._i++ >= this._n && comparer(x, this._elem)) {
6426 this._o.onNext(true);
6427 this._o.onCompleted();
6428 }
6429 };
6430 IncludesObserver.prototype.error = function (e) { this._o.onError(e); };
6431 IncludesObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); };
6432
6433 return IncludesObserver;
6434 }(AbstractObserver));
6435
6436 /**
6437 * Determines whether an observable sequence includes a specified element with an optional equality comparer.
6438 * @param searchElement The value to locate in the source sequence.
6439 * @param {Number} [fromIndex] An equality comparer to compare elements.
6440 * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
6441 */
6442 observableProto.includes = function (searchElement, fromIndex) {
6443 return new IncludesObservable(this, searchElement, fromIndex);
6444 };
6445
6446 var CountObservable = (function (__super__) {
6447 inherits(CountObservable, __super__);
6448 function CountObservable(source, fn) {
6449 this.source = source;
6450 this._fn = fn;
6451 __super__.call(this);
6452 }
6453
6454 CountObservable.prototype.subscribeCore = function (o) {
6455 return this.source.subscribe(new CountObserver(o, this._fn, this.source));
6456 };
6457
6458 return CountObservable;
6459 }(ObservableBase));
6460
6461 var CountObserver = (function (__super__) {
6462 inherits(CountObserver, __super__);
6463
6464 function CountObserver(o, fn, s) {
6465 this._o = o;
6466 this._fn = fn;
6467 this._s = s;
6468 this._i = 0;
6469 this._c = 0;
6470 __super__.call(this);
6471 }
6472
6473 CountObserver.prototype.next = function (x) {
6474 if (this._fn) {
6475 var result = tryCatch(this._fn)(x, this._i++, this._s);
6476 if (result === errorObj) { return this._o.onError(result.e); }
6477 Boolean(result) && (this._c++);
6478 } else {
6479 this._c++;
6480 }
6481 };
6482 CountObserver.prototype.error = function (e) { this._o.onError(e); };
6483 CountObserver.prototype.completed = function () {
6484 this._o.onNext(this._c);
6485 this._o.onCompleted();
6486 };
6487
6488 return CountObserver;
6489 }(AbstractObserver));
6490
6491 /**
6492 * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
6493 * @example
6494 * res = source.count();
6495 * res = source.count(function (x) { return x > 3; });
6496 * @param {Function} [predicate]A function to test each element for a condition.
6497 * @param {Any} [thisArg] Object to use as this when executing callback.
6498 * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
6499 */
6500 observableProto.count = function (predicate, thisArg) {
6501 var fn = bindCallback(predicate, thisArg, 3);
6502 return new CountObservable(this, fn);
6503 };
6504
6505 var IndexOfObservable = (function (__super__) {
6506 inherits(IndexOfObservable, __super__);
6507 function IndexOfObservable(source, e, n) {
6508 this.source = source;
6509 this._e = e;
6510 this._n = n;
6511 __super__.call(this);
6512 }
6513
6514 IndexOfObservable.prototype.subscribeCore = function (o) {
6515 if (this._n < 0) {
6516 o.onNext(-1);
6517 o.onCompleted();
6518 return disposableEmpty;
6519 }
6520
6521 return this.source.subscribe(new IndexOfObserver(o, this._e, this._n));
6522 };
6523
6524 return IndexOfObservable;
6525 }(ObservableBase));
6526
6527 var IndexOfObserver = (function (__super__) {
6528 inherits(IndexOfObserver, __super__);
6529 function IndexOfObserver(o, e, n) {
6530 this._o = o;
6531 this._e = e;
6532 this._n = n;
6533 this._i = 0;
6534 __super__.call(this);
6535 }
6536
6537 IndexOfObserver.prototype.next = function (x) {
6538 if (this._i >= this._n && x === this._e) {
6539 this._o.onNext(this._i);
6540 this._o.onCompleted();
6541 }
6542 this._i++;
6543 };
6544 IndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
6545 IndexOfObserver.prototype.completed = function () { this._o.onNext(-1); this._o.onCompleted(); };
6546
6547 return IndexOfObserver;
6548 }(AbstractObserver));
6549
6550 /**
6551 * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
6552 * @param {Any} searchElement Element to locate in the array.
6553 * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
6554 * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
6555 */
6556 observableProto.indexOf = function(searchElement, fromIndex) {
6557 var n = +fromIndex || 0;
6558 Math.abs(n) === Infinity && (n = 0);
6559 return new IndexOfObservable(this, searchElement, n);
6560 };
6561
6562 var SumObservable = (function (__super__) {
6563 inherits(SumObservable, __super__);
6564 function SumObservable(source, fn) {
6565 this.source = source;
6566 this._fn = fn;
6567 __super__.call(this);
6568 }
6569
6570 SumObservable.prototype.subscribeCore = function (o) {
6571 return this.source.subscribe(new SumObserver(o, this._fn, this.source));
6572 };
6573
6574 return SumObservable;
6575 }(ObservableBase));
6576
6577 var SumObserver = (function (__super__) {
6578 inherits(SumObserver, __super__);
6579
6580 function SumObserver(o, fn, s) {
6581 this._o = o;
6582 this._fn = fn;
6583 this._s = s;
6584 this._i = 0;
6585 this._c = 0;
6586 __super__.call(this);
6587 }
6588
6589 SumObserver.prototype.next = function (x) {
6590 if (this._fn) {
6591 var result = tryCatch(this._fn)(x, this._i++, this._s);
6592 if (result === errorObj) { return this._o.onError(result.e); }
6593 this._c += result;
6594 } else {
6595 this._c += x;
6596 }
6597 };
6598 SumObserver.prototype.error = function (e) { this._o.onError(e); };
6599 SumObserver.prototype.completed = function () {
6600 this._o.onNext(this._c);
6601 this._o.onCompleted();
6602 };
6603
6604 return SumObserver;
6605 }(AbstractObserver));
6606
6607 /**
6608 * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
6609 * @param {Function} [selector] A transform function to apply to each element.
6610 * @param {Any} [thisArg] Object to use as this when executing callback.
6611 * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
6612 */
6613 observableProto.sum = function (keySelector, thisArg) {
6614 var fn = bindCallback(keySelector, thisArg, 3);
6615 return new SumObservable(this, fn);
6616 };
6617
6618 /**
6619 * Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
6620 * @example
6621 * var res = source.minBy(function (x) { return x.value; });
6622 * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
6623 * @param {Function} keySelector Key selector function.
6624 * @param {Function} [comparer] Comparer used to compare key values.
6625 * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
6626 */
6627 observableProto.minBy = function (keySelector, comparer) {
6628 comparer || (comparer = defaultSubComparer);
6629 return new ExtremaByObservable(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
6630 };
6631
6632 /**
6633 * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
6634 * @example
6635 * var res = source.min();
6636 * var res = source.min(function (x, y) { return x.value - y.value; });
6637 * @param {Function} [comparer] Comparer used to compare elements.
6638 * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
6639 */
6640 observableProto.min = function (comparer) {
6641 return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
6642 };
6643
6644 /**
6645 * Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
6646 * @example
6647 * var res = source.maxBy(function (x) { return x.value; });
6648 * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
6649 * @param {Function} keySelector Key selector function.
6650 * @param {Function} [comparer] Comparer used to compare key values.
6651 * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
6652 */
6653 observableProto.maxBy = function (keySelector, comparer) {
6654 comparer || (comparer = defaultSubComparer);
6655 return new ExtremaByObservable(this, keySelector, comparer);
6656 };
6657
6658 /**
6659 * Returns the maximum value in an observable sequence according to the specified comparer.
6660 * @example
6661 * var res = source.max();
6662 * var res = source.max(function (x, y) { return x.value - y.value; });
6663 * @param {Function} [comparer] Comparer used to compare elements.
6664 * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
6665 */
6666 observableProto.max = function (comparer) {
6667 return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
6668 };
6669
6670 var AverageObservable = (function (__super__) {
6671 inherits(AverageObservable, __super__);
6672 function AverageObservable(source, fn) {
6673 this.source = source;
6674 this._fn = fn;
6675 __super__.call(this);
6676 }
6677
6678 AverageObservable.prototype.subscribeCore = function (o) {
6679 return this.source.subscribe(new AverageObserver(o, this._fn, this.source));
6680 };
6681
6682 return AverageObservable;
6683 }(ObservableBase));
6684
6685 var AverageObserver = (function(__super__) {
6686 inherits(AverageObserver, __super__);
6687 function AverageObserver(o, fn, s) {
6688 this._o = o;
6689 this._fn = fn;
6690 this._s = s;
6691 this._c = 0;
6692 this._t = 0;
6693 __super__.call(this);
6694 }
6695
6696 AverageObserver.prototype.next = function (x) {
6697 if(this._fn) {
6698 var r = tryCatch(this._fn)(x, this._c++, this._s);
6699 if (r === errorObj) { return this._o.onError(r.e); }
6700 this._t += r;
6701 } else {
6702 this._c++;
6703 this._t += x;
6704 }
6705 };
6706 AverageObserver.prototype.error = function (e) { this._o.onError(e); };
6707 AverageObserver.prototype.completed = function () {
6708 if (this._c === 0) { return this._o.onError(new EmptyError()); }
6709 this._o.onNext(this._t / this._c);
6710 this._o.onCompleted();
6711 };
6712
6713 return AverageObserver;
6714 }(AbstractObserver));
6715
6716 /**
6717 * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
6718 * @param {Function} [selector] A transform function to apply to each element.
6719 * @param {Any} [thisArg] Object to use as this when executing callback.
6720 * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
6721 */
6722 observableProto.average = function (keySelector, thisArg) {
6723 var source = this, fn;
6724 if (isFunction(keySelector)) {
6725 fn = bindCallback(keySelector, thisArg, 3);
6726 }
6727 return new AverageObservable(source, fn);
6728 };
6729
6730 /**
6731 * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
6732 *
6733 * @example
6734 * var res = res = source.sequenceEqual([1,2,3]);
6735 * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
6736 * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
6737 * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
6738 * @param {Observable} second Second observable sequence or array to compare.
6739 * @param {Function} [comparer] Comparer used to compare elements of both sequences.
6740 * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
6741 */
6742 observableProto.sequenceEqual = function (second, comparer) {
6743 var first = this;
6744 comparer || (comparer = defaultComparer);
6745 return new AnonymousObservable(function (o) {
6746 var donel = false, doner = false, ql = [], qr = [];
6747 var subscription1 = first.subscribe(function (x) {
6748 if (qr.length > 0) {
6749 var v = qr.shift();
6750 var equal = tryCatch(comparer)(v, x);
6751 if (equal === errorObj) { return o.onError(equal.e); }
6752 if (!equal) {
6753 o.onNext(false);
6754 o.onCompleted();
6755 }
6756 } else if (doner) {
6757 o.onNext(false);
6758 o.onCompleted();
6759 } else {
6760 ql.push(x);
6761 }
6762 }, function(e) { o.onError(e); }, function () {
6763 donel = true;
6764 if (ql.length === 0) {
6765 if (qr.length > 0) {
6766 o.onNext(false);
6767 o.onCompleted();
6768 } else if (doner) {
6769 o.onNext(true);
6770 o.onCompleted();
6771 }
6772 }
6773 });
6774
6775 (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
6776 isPromise(second) && (second = observableFromPromise(second));
6777 var subscription2 = second.subscribe(function (x) {
6778 if (ql.length > 0) {
6779 var v = ql.shift();
6780 var equal = tryCatch(comparer)(v, x);
6781 if (equal === errorObj) { return o.onError(equal.e); }
6782 if (!equal) {
6783 o.onNext(false);
6784 o.onCompleted();
6785 }
6786 } else if (donel) {
6787 o.onNext(false);
6788 o.onCompleted();
6789 } else {
6790 qr.push(x);
6791 }
6792 }, function(e) { o.onError(e); }, function () {
6793 doner = true;
6794 if (qr.length === 0) {
6795 if (ql.length > 0) {
6796 o.onNext(false);
6797 o.onCompleted();
6798 } else if (donel) {
6799 o.onNext(true);
6800 o.onCompleted();
6801 }
6802 }
6803 });
6804 return new BinaryDisposable(subscription1, subscription2);
6805 }, first);
6806 };
6807
6808 var ElementAtObservable = (function (__super__) {
6809 inherits(ElementAtObservable, __super__);
6810 function ElementAtObservable(source, i, d) {
6811 this.source = source;
6812 this._i = i;
6813 this._d = d;
6814 __super__.call(this);
6815 }
6816
6817 ElementAtObservable.prototype.subscribeCore = function (o) {
6818 return this.source.subscribe(new ElementAtObserver(o, this._i, this._d));
6819 };
6820
6821 return ElementAtObservable;
6822 }(ObservableBase));
6823
6824 var ElementAtObserver = (function (__super__) {
6825 inherits(ElementAtObserver, __super__);
6826
6827 function ElementAtObserver(o, i, d) {
6828 this._o = o;
6829 this._i = i;
6830 this._d = d;
6831 __super__.call(this);
6832 }
6833
6834 ElementAtObserver.prototype.next = function (x) {
6835 if (this._i-- === 0) {
6836 this._o.onNext(x);
6837 this._o.onCompleted();
6838 }
6839 };
6840 ElementAtObserver.prototype.error = function (e) { this._o.onError(e); };
6841 ElementAtObserver.prototype.completed = function () {
6842 if (this._d === undefined) {
6843 this._o.onError(new ArgumentOutOfRangeError());
6844 } else {
6845 this._o.onNext(this._d);
6846 this._o.onCompleted();
6847 }
6848 };
6849
6850 return ElementAtObserver;
6851 }(AbstractObserver));
6852
6853 /**
6854 * Returns the element at a specified index in a sequence or default value if not found.
6855 * @param {Number} index The zero-based index of the element to retrieve.
6856 * @param {Any} [defaultValue] The default value to use if elementAt does not find a value.
6857 * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
6858 */
6859 observableProto.elementAt = function (index, defaultValue) {
6860 if (index < 0) { throw new ArgumentOutOfRangeError(); }
6861 return new ElementAtObservable(this, index, defaultValue);
6862 };
6863
6864 var SingleObserver = (function(__super__) {
6865 inherits(SingleObserver, __super__);
6866 function SingleObserver(o, obj, s) {
6867 this._o = o;
6868 this._obj = obj;
6869 this._s = s;
6870 this._i = 0;
6871 this._hv = false;
6872 this._v = null;
6873 __super__.call(this);
6874 }
6875
6876 SingleObserver.prototype.next = function (x) {
6877 var shouldYield = false;
6878 if (this._obj.predicate) {
6879 var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
6880 if (res === errorObj) { return this._o.onError(res.e); }
6881 Boolean(res) && (shouldYield = true);
6882 } else if (!this._obj.predicate) {
6883 shouldYield = true;
6884 }
6885 if (shouldYield) {
6886 if (this._hv) {
6887 return this._o.onError(new Error('Sequence contains more than one matching element'));
6888 }
6889 this._hv = true;
6890 this._v = x;
6891 }
6892 };
6893 SingleObserver.prototype.error = function (e) { this._o.onError(e); };
6894 SingleObserver.prototype.completed = function () {
6895 if (this._hv) {
6896 this._o.onNext(this._v);
6897 this._o.onCompleted();
6898 }
6899 else if (this._obj.defaultValue === undefined) {
6900 this._o.onError(new EmptyError());
6901 } else {
6902 this._o.onNext(this._obj.defaultValue);
6903 this._o.onCompleted();
6904 }
6905 };
6906
6907 return SingleObserver;
6908 }(AbstractObserver));
6909
6910
6911 /**
6912 * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
6913 * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
6914 */
6915 observableProto.single = function (predicate, thisArg) {
6916 var obj = {}, source = this;
6917 if (typeof arguments[0] === 'object') {
6918 obj = arguments[0];
6919 } else {
6920 obj = {
6921 predicate: arguments[0],
6922 thisArg: arguments[1],
6923 defaultValue: arguments[2]
6924 };
6925 }
6926 if (isFunction (obj.predicate)) {
6927 var fn = obj.predicate;
6928 obj.predicate = bindCallback(fn, obj.thisArg, 3);
6929 }
6930 return new AnonymousObservable(function (o) {
6931 return source.subscribe(new SingleObserver(o, obj, source));
6932 }, source);
6933 };
6934
6935 var FirstObservable = (function (__super__) {
6936 inherits(FirstObservable, __super__);
6937 function FirstObservable(source, obj) {
6938 this.source = source;
6939 this._obj = obj;
6940 __super__.call(this);
6941 }
6942
6943 FirstObservable.prototype.subscribeCore = function (o) {
6944 return this.source.subscribe(new FirstObserver(o, this._obj, this.source));
6945 };
6946
6947 return FirstObservable;
6948 }(ObservableBase));
6949
6950 var FirstObserver = (function(__super__) {
6951 inherits(FirstObserver, __super__);
6952 function FirstObserver(o, obj, s) {
6953 this._o = o;
6954 this._obj = obj;
6955 this._s = s;
6956 this._i = 0;
6957 __super__.call(this);
6958 }
6959
6960 FirstObserver.prototype.next = function (x) {
6961 if (this._obj.predicate) {
6962 var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
6963 if (res === errorObj) { return this._o.onError(res.e); }
6964 if (Boolean(res)) {
6965 this._o.onNext(x);
6966 this._o.onCompleted();
6967 }
6968 } else if (!this._obj.predicate) {
6969 this._o.onNext(x);
6970 this._o.onCompleted();
6971 }
6972 };
6973 FirstObserver.prototype.error = function (e) { this._o.onError(e); };
6974 FirstObserver.prototype.completed = function () {
6975 if (this._obj.defaultValue === undefined) {
6976 this._o.onError(new EmptyError());
6977 } else {
6978 this._o.onNext(this._obj.defaultValue);
6979 this._o.onCompleted();
6980 }
6981 };
6982
6983 return FirstObserver;
6984 }(AbstractObserver));
6985
6986 /**
6987 * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
6988 * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
6989 */
6990 observableProto.first = function () {
6991 var obj = {}, source = this;
6992 if (typeof arguments[0] === 'object') {
6993 obj = arguments[0];
6994 } else {
6995 obj = {
6996 predicate: arguments[0],
6997 thisArg: arguments[1],
6998 defaultValue: arguments[2]
6999 };
7000 }
7001 if (isFunction (obj.predicate)) {
7002 var fn = obj.predicate;
7003 obj.predicate = bindCallback(fn, obj.thisArg, 3);
7004 }
7005 return new FirstObservable(this, obj);
7006 };
7007
7008 var LastObservable = (function (__super__) {
7009 inherits(LastObservable, __super__);
7010 function LastObservable(source, obj) {
7011 this.source = source;
7012 this._obj = obj;
7013 __super__.call(this);
7014 }
7015
7016 LastObservable.prototype.subscribeCore = function (o) {
7017 return this.source.subscribe(new LastObserver(o, this._obj, this.source));
7018 };
7019
7020 return LastObservable;
7021 }(ObservableBase));
7022
7023 var LastObserver = (function(__super__) {
7024 inherits(LastObserver, __super__);
7025 function LastObserver(o, obj, s) {
7026 this._o = o;
7027 this._obj = obj;
7028 this._s = s;
7029 this._i = 0;
7030 this._hv = false;
7031 this._v = null;
7032 __super__.call(this);
7033 }
7034
7035 LastObserver.prototype.next = function (x) {
7036 var shouldYield = false;
7037 if (this._obj.predicate) {
7038 var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
7039 if (res === errorObj) { return this._o.onError(res.e); }
7040 Boolean(res) && (shouldYield = true);
7041 } else if (!this._obj.predicate) {
7042 shouldYield = true;
7043 }
7044 if (shouldYield) {
7045 this._hv = true;
7046 this._v = x;
7047 }
7048 };
7049 LastObserver.prototype.error = function (e) { this._o.onError(e); };
7050 LastObserver.prototype.completed = function () {
7051 if (this._hv) {
7052 this._o.onNext(this._v);
7053 this._o.onCompleted();
7054 }
7055 else if (this._obj.defaultValue === undefined) {
7056 this._o.onError(new EmptyError());
7057 } else {
7058 this._o.onNext(this._obj.defaultValue);
7059 this._o.onCompleted();
7060 }
7061 };
7062
7063 return LastObserver;
7064 }(AbstractObserver));
7065
7066 /**
7067 * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
7068 * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
7069 */
7070 observableProto.last = function () {
7071 var obj = {}, source = this;
7072 if (typeof arguments[0] === 'object') {
7073 obj = arguments[0];
7074 } else {
7075 obj = {
7076 predicate: arguments[0],
7077 thisArg: arguments[1],
7078 defaultValue: arguments[2]
7079 };
7080 }
7081 if (isFunction (obj.predicate)) {
7082 var fn = obj.predicate;
7083 obj.predicate = bindCallback(fn, obj.thisArg, 3);
7084 }
7085 return new LastObservable(this, obj);
7086 };
7087
7088 var FindValueObserver = (function(__super__) {
7089 inherits(FindValueObserver, __super__);
7090 function FindValueObserver(observer, source, callback, yieldIndex) {
7091 this._o = observer;
7092 this._s = source;
7093 this._cb = callback;
7094 this._y = yieldIndex;
7095 this._i = 0;
7096 __super__.call(this);
7097 }
7098
7099 FindValueObserver.prototype.next = function (x) {
7100 var shouldRun = tryCatch(this._cb)(x, this._i, this._s);
7101 if (shouldRun === errorObj) { return this._o.onError(shouldRun.e); }
7102 if (shouldRun) {
7103 this._o.onNext(this._y ? this._i : x);
7104 this._o.onCompleted();
7105 } else {
7106 this._i++;
7107 }
7108 };
7109
7110 FindValueObserver.prototype.error = function (e) {
7111 this._o.onError(e);
7112 };
7113
7114 FindValueObserver.prototype.completed = function () {
7115 this._y && this._o.onNext(-1);
7116 this._o.onCompleted();
7117 };
7118
7119 return FindValueObserver;
7120 }(AbstractObserver));
7121
7122 function findValue (source, predicate, thisArg, yieldIndex) {
7123 var callback = bindCallback(predicate, thisArg, 3);
7124 return new AnonymousObservable(function (o) {
7125 return source.subscribe(new FindValueObserver(o, source, callback, yieldIndex));
7126 }, source);
7127 }
7128
7129 /**
7130 * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
7131 * @param {Function} predicate The predicate that defines the conditions of the element to search for.
7132 * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
7133 * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
7134 */
7135 observableProto.find = function (predicate, thisArg) {
7136 return findValue(this, predicate, thisArg, false);
7137 };
7138
7139 /**
7140 * Searches for an element that matches the conditions defined by the specified predicate, and returns
7141 * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
7142 * @param {Function} predicate The predicate that defines the conditions of the element to search for.
7143 * @param {Any} [thisArg] Object to use as `this` when executing the predicate.
7144 * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
7145 */
7146 observableProto.findIndex = function (predicate, thisArg) {
7147 return findValue(this, predicate, thisArg, true);
7148 };
7149
7150 var ToSetObservable = (function (__super__) {
7151 inherits(ToSetObservable, __super__);
7152 function ToSetObservable(source) {
7153 this.source = source;
7154 __super__.call(this);
7155 }
7156
7157 ToSetObservable.prototype.subscribeCore = function (o) {
7158 return this.source.subscribe(new ToSetObserver(o));
7159 };
7160
7161 return ToSetObservable;
7162 }(ObservableBase));
7163
7164 var ToSetObserver = (function (__super__) {
7165 inherits(ToSetObserver, __super__);
7166 function ToSetObserver(o) {
7167 this._o = o;
7168 this._s = new root.Set();
7169 __super__.call(this);
7170 }
7171
7172 ToSetObserver.prototype.next = function (x) {
7173 this._s.add(x);
7174 };
7175
7176 ToSetObserver.prototype.error = function (e) {
7177 this._o.onError(e);
7178 };
7179
7180 ToSetObserver.prototype.completed = function () {
7181 this._o.onNext(this._s);
7182 this._o.onCompleted();
7183 };
7184
7185 return ToSetObserver;
7186 }(AbstractObserver));
7187
7188 /**
7189 * Converts the observable sequence to a Set if it exists.
7190 * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
7191 */
7192 observableProto.toSet = function () {
7193 if (typeof root.Set === 'undefined') { throw new TypeError(); }
7194 return new ToSetObservable(this);
7195 };
7196
7197 var ToMapObservable = (function (__super__) {
7198 inherits(ToMapObservable, __super__);
7199 function ToMapObservable(source, k, e) {
7200 this.source = source;
7201 this._k = k;
7202 this._e = e;
7203 __super__.call(this);
7204 }
7205
7206 ToMapObservable.prototype.subscribeCore = function (o) {
7207 return this.source.subscribe(new ToMapObserver(o, this._k, this._e));
7208 };
7209
7210 return ToMapObservable;
7211 }(ObservableBase));
7212
7213 var ToMapObserver = (function (__super__) {
7214 inherits(ToMapObserver, __super__);
7215 function ToMapObserver(o, k, e) {
7216 this._o = o;
7217 this._k = k;
7218 this._e = e;
7219 this._m = new root.Map();
7220 __super__.call(this);
7221 }
7222
7223 ToMapObserver.prototype.next = function (x) {
7224 var key = tryCatch(this._k)(x);
7225 if (key === errorObj) { return this._o.onError(key.e); }
7226 var elem = x;
7227 if (this._e) {
7228 elem = tryCatch(this._e)(x);
7229 if (elem === errorObj) { return this._o.onError(elem.e); }
7230 }
7231
7232 this._m.set(key, elem);
7233 };
7234
7235 ToMapObserver.prototype.error = function (e) {
7236 this._o.onError(e);
7237 };
7238
7239 ToMapObserver.prototype.completed = function () {
7240 this._o.onNext(this._m);
7241 this._o.onCompleted();
7242 };
7243
7244 return ToMapObserver;
7245 }(AbstractObserver));
7246
7247 /**
7248 * Converts the observable sequence to a Map if it exists.
7249 * @param {Function} keySelector A function which produces the key for the Map.
7250 * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
7251 * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
7252 */
7253 observableProto.toMap = function (keySelector, elementSelector) {
7254 if (typeof root.Map === 'undefined') { throw new TypeError(); }
7255 return new ToMapObservable(this, keySelector, elementSelector);
7256 };
7257
7258 var SliceObservable = (function (__super__) {
7259 inherits(SliceObservable, __super__);
7260 function SliceObservable(source, b, e) {
7261 this.source = source;
7262 this._b = b;
7263 this._e = e;
7264 __super__.call(this);
7265 }
7266
7267 SliceObservable.prototype.subscribeCore = function (o) {
7268 return this.source.subscribe(new SliceObserver(o, this._b, this._e));
7269 };
7270
7271 return SliceObservable;
7272 }(ObservableBase));
7273
7274 var SliceObserver = (function (__super__) {
7275 inherits(SliceObserver, __super__);
7276
7277 function SliceObserver(o, b, e) {
7278 this._o = o;
7279 this._b = b;
7280 this._e = e;
7281 this._i = 0;
7282 __super__.call(this);
7283 }
7284
7285 SliceObserver.prototype.next = function (x) {
7286 if (this._i >= this._b) {
7287 if (this._e === this._i) {
7288 this._o.onCompleted();
7289 } else {
7290 this._o.onNext(x);
7291 }
7292 }
7293 this._i++;
7294 };
7295 SliceObserver.prototype.error = function (e) { this._o.onError(e); };
7296 SliceObserver.prototype.completed = function () { this._o.onCompleted(); };
7297
7298 return SliceObserver;
7299 }(AbstractObserver));
7300
7301 /*
7302 * The slice() method returns a shallow copy of a portion of an Observable into a new Observable object.
7303 * Unlike the array version, this does not support negative numbers for being or end.
7304 * @param {Number} [begin] Zero-based index at which to begin extraction. If omitted, this will default to zero.
7305 * @param {Number} [end] Zero-based index at which to end extraction. slice extracts up to but not including end.
7306 * If omitted, this will emit the rest of the Observable object.
7307 * @returns {Observable} A shallow copy of a portion of an Observable into a new Observable object.
7308 */
7309 observableProto.slice = function (begin, end) {
7310 var start = begin || 0;
7311 if (start < 0) { throw new Rx.ArgumentOutOfRangeError(); }
7312 if (typeof end === 'number' && end < start) {
7313 throw new Rx.ArgumentOutOfRangeError();
7314 }
7315 return new SliceObservable(this, start, end);
7316 };
7317
7318 var LastIndexOfObservable = (function (__super__) {
7319 inherits(LastIndexOfObservable, __super__);
7320 function LastIndexOfObservable(source, e, n) {
7321 this.source = source;
7322 this._e = e;
7323 this._n = n;
7324 __super__.call(this);
7325 }
7326
7327 LastIndexOfObservable.prototype.subscribeCore = function (o) {
7328 if (this._n < 0) {
7329 o.onNext(-1);
7330 o.onCompleted();
7331 return disposableEmpty;
7332 }
7333
7334 return this.source.subscribe(new LastIndexOfObserver(o, this._e, this._n));
7335 };
7336
7337 return LastIndexOfObservable;
7338 }(ObservableBase));
7339
7340 var LastIndexOfObserver = (function (__super__) {
7341 inherits(LastIndexOfObserver, __super__);
7342 function LastIndexOfObserver(o, e, n) {
7343 this._o = o;
7344 this._e = e;
7345 this._n = n;
7346 this._v = 0;
7347 this._hv = false;
7348 this._i = 0;
7349 __super__.call(this);
7350 }
7351
7352 LastIndexOfObserver.prototype.next = function (x) {
7353 if (this._i >= this._n && x === this._e) {
7354 this._hv = true;
7355 this._v = this._i;
7356 }
7357 this._i++;
7358 };
7359 LastIndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
7360 LastIndexOfObserver.prototype.completed = function () {
7361 if (this._hv) {
7362 this._o.onNext(this._v);
7363 } else {
7364 this._o.onNext(-1);
7365 }
7366 this._o.onCompleted();
7367 };
7368
7369 return LastIndexOfObserver;
7370 }(AbstractObserver));
7371
7372 /**
7373 * Returns the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
7374 * @param {Any} searchElement Element to locate in the array.
7375 * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
7376 * @returns {Observable} And observable sequence containing the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
7377 */
7378 observableProto.lastIndexOf = function(searchElement, fromIndex) {
7379 var n = +fromIndex || 0;
7380 Math.abs(n) === Infinity && (n = 0);
7381 return new LastIndexOfObservable(this, searchElement, n);
7382 };
7383
7384 Observable.wrap = function (fn) {
7385 function createObservable() {
7386 return Observable.spawn.call(this, fn.apply(this, arguments));
7387 }
7388
7389 createObservable.__generatorFunction__ = fn;
7390 return createObservable;
7391 };
7392
7393 var spawn = Observable.spawn = function () {
7394 var gen = arguments[0], self = this, args = [];
7395 for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
7396
7397 return new AnonymousObservable(function (o) {
7398 var g = new CompositeDisposable();
7399
7400 if (isFunction(gen)) { gen = gen.apply(self, args); }
7401 if (!gen || !isFunction(gen.next)) {
7402 o.onNext(gen);
7403 return o.onCompleted();
7404 }
7405
7406 function processGenerator(res) {
7407 var ret = tryCatch(gen.next).call(gen, res);
7408 if (ret === errorObj) { return o.onError(ret.e); }
7409 next(ret);
7410 }
7411
7412 processGenerator();
7413
7414 function onError(err) {
7415 var ret = tryCatch(gen.next).call(gen, err);
7416 if (ret === errorObj) { return o.onError(ret.e); }
7417 next(ret);
7418 }
7419
7420 function next(ret) {
7421 if (ret.done) {
7422 o.onNext(ret.value);
7423 o.onCompleted();
7424 return;
7425 }
7426 var obs = toObservable.call(self, ret.value);
7427 var value = null;
7428 var hasValue = false;
7429 if (Observable.isObservable(obs)) {
7430 g.add(obs.subscribe(function(val) {
7431 hasValue = true;
7432 value = val;
7433 }, onError, function() {
7434 hasValue && processGenerator(value);
7435 }));
7436 } else {
7437 onError(new TypeError('type not supported'));
7438 }
7439 }
7440
7441 return g;
7442 });
7443 };
7444
7445 function toObservable(obj) {
7446 if (!obj) { return obj; }
7447 if (Observable.isObservable(obj)) { return obj; }
7448 if (isPromise(obj)) { return Observable.fromPromise(obj); }
7449 if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); }
7450 if (isFunction(obj)) { return thunkToObservable.call(this, obj); }
7451 if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); }
7452 if (isObject(obj)) {return objectToObservable.call(this, obj);}
7453 return obj;
7454 }
7455
7456 function arrayToObservable (obj) {
7457 return Observable.from(obj).concatMap(function(o) {
7458 if(Observable.isObservable(o) || isObject(o)) {
7459 return toObservable.call(null, o);
7460 } else {
7461 return Rx.Observable.just(o);
7462 }
7463 }).toArray();
7464 }
7465
7466 function objectToObservable (obj) {
7467 var results = new obj.constructor(), keys = Object.keys(obj), observables = [];
7468 for (var i = 0, len = keys.length; i < len; i++) {
7469 var key = keys[i];
7470 var observable = toObservable.call(this, obj[key]);
7471
7472 if(observable && Observable.isObservable(observable)) {
7473 defer(observable, key);
7474 } else {
7475 results[key] = obj[key];
7476 }
7477 }
7478
7479 return Observable.forkJoin.apply(Observable, observables).map(function() {
7480 return results;
7481 });
7482
7483
7484 function defer (observable, key) {
7485 results[key] = undefined;
7486 observables.push(observable.map(function (next) {
7487 results[key] = next;
7488 }));
7489 }
7490 }
7491
7492 function thunkToObservable(fn) {
7493 var self = this;
7494 return new AnonymousObservable(function (o) {
7495 fn.call(self, function () {
7496 var err = arguments[0], res = arguments[1];
7497 if (err) { return o.onError(err); }
7498 if (arguments.length > 2) {
7499 var args = [];
7500 for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
7501 res = args;
7502 }
7503 o.onNext(res);
7504 o.onCompleted();
7505 });
7506 });
7507 }
7508
7509 function isGenerator(obj) {
7510 return isFunction (obj.next) && isFunction (obj['throw']);
7511 }
7512
7513 function isGeneratorFunction(obj) {
7514 var ctor = obj.constructor;
7515 if (!ctor) { return false; }
7516 if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; }
7517 return isGenerator(ctor.prototype);
7518 }
7519
7520 function isObject(val) {
7521 return Object == val.constructor;
7522 }
7523
7524 /**
7525 * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
7526 *
7527 * @example
7528 * var res = Rx.Observable.start(function () { console.log('hello'); });
7529 * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
7530 * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
7531 *
7532 * @param {Function} func Function to run asynchronously.
7533 * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
7534 * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
7535 * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
7536 *
7537 * Remarks
7538 * * The function is called immediately, not during the subscription of the resulting sequence.
7539 * * Multiple subscriptions to the resulting sequence can observe the function's result.
7540 */
7541 Observable.start = function (func, context, scheduler) {
7542 return observableToAsync(func, context, scheduler)();
7543 };
7544
7545 /**
7546 * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
7547 * @param {Function} function Function to convert to an asynchronous function.
7548 * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
7549 * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
7550 * @returns {Function} Asynchronous function.
7551 */
7552 var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
7553 isScheduler(scheduler) || (scheduler = defaultScheduler);
7554 return function () {
7555 var args = arguments,
7556 subject = new AsyncSubject();
7557
7558 scheduler.schedule(null, function () {
7559 var result;
7560 try {
7561 result = func.apply(context, args);
7562 } catch (e) {
7563 subject.onError(e);
7564 return;
7565 }
7566 subject.onNext(result);
7567 subject.onCompleted();
7568 });
7569 return subject.asObservable();
7570 };
7571 };
7572
7573function createCbObservable(fn, ctx, selector, args) {
7574 var o = new AsyncSubject();
7575
7576 args.push(createCbHandler(o, ctx, selector));
7577 fn.apply(ctx, args);
7578
7579 return o.asObservable();
7580}
7581
7582function createCbHandler(o, ctx, selector) {
7583 return function handler () {
7584 var len = arguments.length, results = new Array(len);
7585 for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
7586
7587 if (isFunction(selector)) {
7588 results = tryCatch(selector).apply(ctx, results);
7589 if (results === errorObj) { return o.onError(results.e); }
7590 o.onNext(results);
7591 } else {
7592 if (results.length <= 1) {
7593 o.onNext(results[0]);
7594 } else {
7595 o.onNext(results);
7596 }
7597 }
7598
7599 o.onCompleted();
7600 };
7601}
7602
7603/**
7604 * Converts a callback function to an observable sequence.
7605 *
7606 * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence.
7607 * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
7608 * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
7609 * @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.
7610 */
7611Observable.fromCallback = function (fn, ctx, selector) {
7612 return function () {
7613 typeof ctx === 'undefined' && (ctx = this);
7614
7615 var len = arguments.length, args = new Array(len)
7616 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
7617 return createCbObservable(fn, ctx, selector, args);
7618 };
7619};
7620
7621function createNodeObservable(fn, ctx, selector, args) {
7622 var o = new AsyncSubject();
7623
7624 args.push(createNodeHandler(o, ctx, selector));
7625 fn.apply(ctx, args);
7626
7627 return o.asObservable();
7628}
7629
7630function createNodeHandler(o, ctx, selector) {
7631 return function handler () {
7632 var err = arguments[0];
7633 if (err) { return o.onError(err); }
7634
7635 var len = arguments.length, results = [];
7636 for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
7637
7638 if (isFunction(selector)) {
7639 var results = tryCatch(selector).apply(ctx, results);
7640 if (results === errorObj) { return o.onError(results.e); }
7641 o.onNext(results);
7642 } else {
7643 if (results.length <= 1) {
7644 o.onNext(results[0]);
7645 } else {
7646 o.onNext(results);
7647 }
7648 }
7649
7650 o.onCompleted();
7651 };
7652}
7653
7654/**
7655 * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
7656 * @param {Function} fn The function to call
7657 * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
7658 * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
7659 * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
7660 */
7661Observable.fromNodeCallback = function (fn, ctx, selector) {
7662 return function () {
7663 typeof ctx === 'undefined' && (ctx = this);
7664 var len = arguments.length, args = new Array(len);
7665 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
7666 return createNodeObservable(fn, ctx, selector, args);
7667 };
7668};
7669
7670 function isNodeList(el) {
7671 if (root.StaticNodeList) {
7672 // IE8 Specific
7673 // instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8
7674 return el instanceof root.StaticNodeList || el instanceof root.NodeList;
7675 } else {
7676 return Object.prototype.toString.call(el) === '[object NodeList]';
7677 }
7678 }
7679
7680 function ListenDisposable(e, n, fn) {
7681 this._e = e;
7682 this._n = n;
7683 this._fn = fn;
7684 this._e.addEventListener(this._n, this._fn, false);
7685 this.isDisposed = false;
7686 }
7687 ListenDisposable.prototype.dispose = function () {
7688 if (!this.isDisposed) {
7689 this._e.removeEventListener(this._n, this._fn, false);
7690 this.isDisposed = true;
7691 }
7692 };
7693
7694 function createEventListener (el, eventName, handler) {
7695 var disposables = new CompositeDisposable();
7696
7697 // Asume NodeList or HTMLCollection
7698 var elemToString = Object.prototype.toString.call(el);
7699 if (isNodeList(el) || elemToString === '[object HTMLCollection]') {
7700 for (var i = 0, len = el.length; i < len; i++) {
7701 disposables.add(createEventListener(el.item(i), eventName, handler));
7702 }
7703 } else if (el) {
7704 disposables.add(new ListenDisposable(el, eventName, handler));
7705 }
7706
7707 return disposables;
7708 }
7709
7710 /**
7711 * Configuration option to determine whether to use native events only
7712 */
7713 Rx.config.useNativeEvents = false;
7714
7715 var EventObservable = (function(__super__) {
7716 inherits(EventObservable, __super__);
7717 function EventObservable(el, name, fn) {
7718 this._el = el;
7719 this._n = name;
7720 this._fn = fn;
7721 __super__.call(this);
7722 }
7723
7724 function createHandler(o, fn) {
7725 return function handler () {
7726 var results = arguments[0];
7727 if (isFunction(fn)) {
7728 results = tryCatch(fn).apply(null, arguments);
7729 if (results === errorObj) { return o.onError(results.e); }
7730 }
7731 o.onNext(results);
7732 };
7733 }
7734
7735 EventObservable.prototype.subscribeCore = function (o) {
7736 return createEventListener(
7737 this._el,
7738 this._n,
7739 createHandler(o, this._fn));
7740 };
7741
7742 return EventObservable;
7743 }(ObservableBase));
7744
7745 /**
7746 * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
7747 * @param {Object} element The DOMElement or NodeList to attach a listener.
7748 * @param {String} eventName The event name to attach the observable sequence.
7749 * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
7750 * @returns {Observable} An observable sequence of events from the specified element and the specified event.
7751 */
7752 Observable.fromEvent = function (element, eventName, selector) {
7753 // Node.js specific
7754 if (element.addListener) {
7755 return fromEventPattern(
7756 function (h) { element.addListener(eventName, h); },
7757 function (h) { element.removeListener(eventName, h); },
7758 selector);
7759 }
7760
7761 // Use only if non-native events are allowed
7762 if (!Rx.config.useNativeEvents) {
7763 // Handles jq, Angular.js, Zepto, Marionette, Ember.js
7764 if (typeof element.on === 'function' && typeof element.off === 'function') {
7765 return fromEventPattern(
7766 function (h) { element.on(eventName, h); },
7767 function (h) { element.off(eventName, h); },
7768 selector);
7769 }
7770 }
7771
7772 return new EventObservable(element, eventName, selector).publish().refCount();
7773 };
7774
7775 var EventPatternObservable = (function(__super__) {
7776 inherits(EventPatternObservable, __super__);
7777 function EventPatternObservable(add, del, fn) {
7778 this._add = add;
7779 this._del = del;
7780 this._fn = fn;
7781 __super__.call(this);
7782 }
7783
7784 function createHandler(o, fn) {
7785 return function handler () {
7786 var results = arguments[0];
7787 if (isFunction(fn)) {
7788 results = tryCatch(fn).apply(null, arguments);
7789 if (results === errorObj) { return o.onError(results.e); }
7790 }
7791 o.onNext(results);
7792 };
7793 }
7794
7795 EventPatternObservable.prototype.subscribeCore = function (o) {
7796 var fn = createHandler(o, this._fn);
7797 var returnValue = this._add(fn);
7798 return new EventPatternDisposable(this._del, fn, returnValue);
7799 };
7800
7801 function EventPatternDisposable(del, fn, ret) {
7802 this._del = del;
7803 this._fn = fn;
7804 this._ret = ret;
7805 this.isDisposed = false;
7806 }
7807
7808 EventPatternDisposable.prototype.dispose = function () {
7809 if(!this.isDisposed) {
7810 isFunction(this._del) && this._del(this._fn, this._ret);
7811 }
7812 };
7813
7814 return EventPatternObservable;
7815 }(ObservableBase));
7816
7817 /**
7818 * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
7819 * @param {Function} addHandler The function to add a handler to the emitter.
7820 * @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
7821 * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
7822 * @returns {Observable} An observable sequence which wraps an event from an event emitter
7823 */
7824 var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
7825 return new EventPatternObservable(addHandler, removeHandler, selector).publish().refCount();
7826 };
7827
7828 /**
7829 * Invokes the asynchronous function, surfacing the result through an observable sequence.
7830 * @param {Function} functionAsync Asynchronous function which returns a Promise to run.
7831 * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
7832 */
7833 Observable.startAsync = function (functionAsync) {
7834 var promise = tryCatch(functionAsync)();
7835 if (promise === errorObj) { return observableThrow(promise.e); }
7836 return observableFromPromise(promise);
7837 };
7838
7839 var PausableObservable = (function (__super__) {
7840 inherits(PausableObservable, __super__);
7841 function PausableObservable(source, pauser) {
7842 this.source = source;
7843 this.controller = new Subject();
7844
7845 if (pauser && pauser.subscribe) {
7846 this.pauser = this.controller.merge(pauser);
7847 } else {
7848 this.pauser = this.controller;
7849 }
7850
7851 __super__.call(this);
7852 }
7853
7854 PausableObservable.prototype._subscribe = function (o) {
7855 var conn = this.source.publish(),
7856 subscription = conn.subscribe(o),
7857 connection = disposableEmpty;
7858
7859 var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
7860 if (b) {
7861 connection = conn.connect();
7862 } else {
7863 connection.dispose();
7864 connection = disposableEmpty;
7865 }
7866 });
7867
7868 return new NAryDisposable([subscription, connection, pausable]);
7869 };
7870
7871 PausableObservable.prototype.pause = function () {
7872 this.controller.onNext(false);
7873 };
7874
7875 PausableObservable.prototype.resume = function () {
7876 this.controller.onNext(true);
7877 };
7878
7879 return PausableObservable;
7880
7881 }(Observable));
7882
7883 /**
7884 * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
7885 * @example
7886 * var pauser = new Rx.Subject();
7887 * var source = Rx.Observable.interval(100).pausable(pauser);
7888 * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
7889 * @returns {Observable} The observable sequence which is paused based upon the pauser.
7890 */
7891 observableProto.pausable = function (pauser) {
7892 return new PausableObservable(this, pauser);
7893 };
7894
7895 function combineLatestSource(source, subject, resultSelector) {
7896 return new AnonymousObservable(function (o) {
7897 var hasValue = [false, false],
7898 hasValueAll = false,
7899 isDone = false,
7900 values = new Array(2),
7901 err;
7902
7903 function next(x, i) {
7904 values[i] = x;
7905 hasValue[i] = true;
7906 if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
7907 if (err) { return o.onError(err); }
7908 var res = tryCatch(resultSelector).apply(null, values);
7909 if (res === errorObj) { return o.onError(res.e); }
7910 o.onNext(res);
7911 }
7912 isDone && values[1] && o.onCompleted();
7913 }
7914
7915 return new BinaryDisposable(
7916 source.subscribe(
7917 function (x) {
7918 next(x, 0);
7919 },
7920 function (e) {
7921 if (values[1]) {
7922 o.onError(e);
7923 } else {
7924 err = e;
7925 }
7926 },
7927 function () {
7928 isDone = true;
7929 values[1] && o.onCompleted();
7930 }),
7931 subject.subscribe(
7932 function (x) {
7933 next(x, 1);
7934 },
7935 function (e) { o.onError(e); },
7936 function () {
7937 isDone = true;
7938 next(true, 1);
7939 })
7940 );
7941 }, source);
7942 }
7943
7944 var PausableBufferedObservable = (function (__super__) {
7945 inherits(PausableBufferedObservable, __super__);
7946 function PausableBufferedObservable(source, pauser) {
7947 this.source = source;
7948 this.controller = new Subject();
7949
7950 if (pauser && pauser.subscribe) {
7951 this.pauser = this.controller.merge(pauser);
7952 } else {
7953 this.pauser = this.controller;
7954 }
7955
7956 __super__.call(this);
7957 }
7958
7959 PausableBufferedObservable.prototype._subscribe = function (o) {
7960 var q = [], previousShouldFire;
7961
7962 function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
7963
7964 var subscription =
7965 combineLatestSource(
7966 this.source,
7967 this.pauser.startWith(false).distinctUntilChanged(),
7968 function (data, shouldFire) {
7969 return { data: data, shouldFire: shouldFire };
7970 })
7971 .subscribe(
7972 function (results) {
7973 if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) {
7974 previousShouldFire = results.shouldFire;
7975 // change in shouldFire
7976 if (results.shouldFire) { drainQueue(); }
7977 } else {
7978 previousShouldFire = results.shouldFire;
7979 // new data
7980 if (results.shouldFire) {
7981 o.onNext(results.data);
7982 } else {
7983 q.push(results.data);
7984 }
7985 }
7986 },
7987 function (err) {
7988 drainQueue();
7989 o.onError(err);
7990 },
7991 function () {
7992 drainQueue();
7993 o.onCompleted();
7994 }
7995 );
7996 return subscription;
7997 };
7998
7999 PausableBufferedObservable.prototype.pause = function () {
8000 this.controller.onNext(false);
8001 };
8002
8003 PausableBufferedObservable.prototype.resume = function () {
8004 this.controller.onNext(true);
8005 };
8006
8007 return PausableBufferedObservable;
8008
8009 }(Observable));
8010
8011 /**
8012 * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
8013 * and yields the values that were buffered while paused.
8014 * @example
8015 * var pauser = new Rx.Subject();
8016 * var source = Rx.Observable.interval(100).pausableBuffered(pauser);
8017 * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
8018 * @returns {Observable} The observable sequence which is paused based upon the pauser.
8019 */
8020 observableProto.pausableBuffered = function (pauser) {
8021 return new PausableBufferedObservable(this, pauser);
8022 };
8023
8024 var ControlledObservable = (function (__super__) {
8025 inherits(ControlledObservable, __super__);
8026 function ControlledObservable (source, enableQueue, scheduler) {
8027 __super__.call(this);
8028 this.subject = new ControlledSubject(enableQueue, scheduler);
8029 this.source = source.multicast(this.subject).refCount();
8030 }
8031
8032 ControlledObservable.prototype._subscribe = function (o) {
8033 return this.source.subscribe(o);
8034 };
8035
8036 ControlledObservable.prototype.request = function (numberOfItems) {
8037 return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
8038 };
8039
8040 return ControlledObservable;
8041
8042 }(Observable));
8043
8044 var ControlledSubject = (function (__super__) {
8045 inherits(ControlledSubject, __super__);
8046 function ControlledSubject(enableQueue, scheduler) {
8047 enableQueue == null && (enableQueue = true);
8048
8049 __super__.call(this);
8050 this.subject = new Subject();
8051 this.enableQueue = enableQueue;
8052 this.queue = enableQueue ? [] : null;
8053 this.requestedCount = 0;
8054 this.requestedDisposable = null;
8055 this.error = null;
8056 this.hasFailed = false;
8057 this.hasCompleted = false;
8058 this.scheduler = scheduler || currentThreadScheduler;
8059 }
8060
8061 addProperties(ControlledSubject.prototype, Observer, {
8062 _subscribe: function (o) {
8063 return this.subject.subscribe(o);
8064 },
8065 onCompleted: function () {
8066 this.hasCompleted = true;
8067 if (!this.enableQueue || this.queue.length === 0) {
8068 this.subject.onCompleted();
8069 this.disposeCurrentRequest();
8070 } else {
8071 this.queue.push(Notification.createOnCompleted());
8072 }
8073 },
8074 onError: function (error) {
8075 this.hasFailed = true;
8076 this.error = error;
8077 if (!this.enableQueue || this.queue.length === 0) {
8078 this.subject.onError(error);
8079 this.disposeCurrentRequest();
8080 } else {
8081 this.queue.push(Notification.createOnError(error));
8082 }
8083 },
8084 onNext: function (value) {
8085 if (this.requestedCount <= 0) {
8086 this.enableQueue && this.queue.push(Notification.createOnNext(value));
8087 } else {
8088 (this.requestedCount-- === 0) && this.disposeCurrentRequest();
8089 this.subject.onNext(value);
8090 }
8091 },
8092 _processRequest: function (numberOfItems) {
8093 if (this.enableQueue) {
8094 while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {
8095 var first = this.queue.shift();
8096 first.accept(this.subject);
8097 if (first.kind === 'N') {
8098 numberOfItems--;
8099 } else {
8100 this.disposeCurrentRequest();
8101 this.queue = [];
8102 }
8103 }
8104 }
8105
8106 return numberOfItems;
8107 },
8108 request: function (number) {
8109 this.disposeCurrentRequest();
8110 var self = this;
8111
8112 this.requestedDisposable = this.scheduler.schedule(number,
8113 function(s, i) {
8114 var remaining = self._processRequest(i);
8115 var stopped = self.hasCompleted || self.hasFailed;
8116 if (!stopped && remaining > 0) {
8117 self.requestedCount = remaining;
8118
8119 return disposableCreate(function () {
8120 self.requestedCount = 0;
8121 });
8122 // Scheduled item is still in progress. Return a new
8123 // disposable to allow the request to be interrupted
8124 // via dispose.
8125 }
8126 });
8127
8128 return this.requestedDisposable;
8129 },
8130 disposeCurrentRequest: function () {
8131 if (this.requestedDisposable) {
8132 this.requestedDisposable.dispose();
8133 this.requestedDisposable = null;
8134 }
8135 }
8136 });
8137
8138 return ControlledSubject;
8139 }(Observable));
8140
8141 /**
8142 * Attaches a controller to the observable sequence with the ability to queue.
8143 * @example
8144 * var source = Rx.Observable.interval(100).controlled();
8145 * source.request(3); // Reads 3 values
8146 * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
8147 * @param {Scheduler} scheduler determines how the requests will be scheduled
8148 * @returns {Observable} The observable sequence which only propagates values on request.
8149 */
8150 observableProto.controlled = function (enableQueue, scheduler) {
8151
8152 if (enableQueue && isScheduler(enableQueue)) {
8153 scheduler = enableQueue;
8154 enableQueue = true;
8155 }
8156
8157 if (enableQueue == null) { enableQueue = true; }
8158 return new ControlledObservable(this, enableQueue, scheduler);
8159 };
8160
8161 var StopAndWaitObservable = (function (__super__) {
8162 inherits(StopAndWaitObservable, __super__);
8163 function StopAndWaitObservable (source) {
8164 __super__.call(this);
8165 this.source = source;
8166 }
8167
8168 function scheduleMethod(s, self) {
8169 self.source.request(1);
8170 }
8171
8172 StopAndWaitObservable.prototype._subscribe = function (o) {
8173 this.subscription = this.source.subscribe(new StopAndWaitObserver(o, this, this.subscription));
8174 return new BinaryDisposable(
8175 this.subscription,
8176 defaultScheduler.schedule(this, scheduleMethod)
8177 );
8178 };
8179
8180 var StopAndWaitObserver = (function (__sub__) {
8181 inherits(StopAndWaitObserver, __sub__);
8182 function StopAndWaitObserver (observer, observable, cancel) {
8183 __sub__.call(this);
8184 this.observer = observer;
8185 this.observable = observable;
8186 this.cancel = cancel;
8187 this.scheduleDisposable = null;
8188 }
8189
8190 StopAndWaitObserver.prototype.completed = function () {
8191 this.observer.onCompleted();
8192 this.dispose();
8193 };
8194
8195 StopAndWaitObserver.prototype.error = function (error) {
8196 this.observer.onError(error);
8197 this.dispose();
8198 };
8199
8200 function innerScheduleMethod(s, self) {
8201 self.observable.source.request(1);
8202 }
8203
8204 StopAndWaitObserver.prototype.next = function (value) {
8205 this.observer.onNext(value);
8206 this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod);
8207 };
8208
8209 StopAndWaitObservable.dispose = function () {
8210 this.observer = null;
8211 if (this.cancel) {
8212 this.cancel.dispose();
8213 this.cancel = null;
8214 }
8215 if (this.scheduleDisposable) {
8216 this.scheduleDisposable.dispose();
8217 this.scheduleDisposable = null;
8218 }
8219 __sub__.prototype.dispose.call(this);
8220 };
8221
8222 return StopAndWaitObserver;
8223 }(AbstractObserver));
8224
8225 return StopAndWaitObservable;
8226 }(Observable));
8227
8228
8229 /**
8230 * Attaches a stop and wait observable to the current observable.
8231 * @returns {Observable} A stop and wait observable.
8232 */
8233 ControlledObservable.prototype.stopAndWait = function () {
8234 return new StopAndWaitObservable(this);
8235 };
8236
8237 var WindowedObservable = (function (__super__) {
8238 inherits(WindowedObservable, __super__);
8239 function WindowedObservable(source, windowSize) {
8240 __super__.call(this);
8241 this.source = source;
8242 this.windowSize = windowSize;
8243 }
8244
8245 function scheduleMethod(s, self) {
8246 self.source.request(self.windowSize);
8247 }
8248
8249 WindowedObservable.prototype._subscribe = function (o) {
8250 this.subscription = this.source.subscribe(new WindowedObserver(o, this, this.subscription));
8251 return new BinaryDisposable(
8252 this.subscription,
8253 defaultScheduler.schedule(this, scheduleMethod)
8254 );
8255 };
8256
8257 var WindowedObserver = (function (__sub__) {
8258 inherits(WindowedObserver, __sub__);
8259 function WindowedObserver(observer, observable, cancel) {
8260 this.observer = observer;
8261 this.observable = observable;
8262 this.cancel = cancel;
8263 this.received = 0;
8264 this.scheduleDisposable = null;
8265 __sub__.call(this);
8266 }
8267
8268 WindowedObserver.prototype.completed = function () {
8269 this.observer.onCompleted();
8270 this.dispose();
8271 };
8272
8273 WindowedObserver.prototype.error = function (error) {
8274 this.observer.onError(error);
8275 this.dispose();
8276 };
8277
8278 function innerScheduleMethod(s, self) {
8279 self.observable.source.request(self.observable.windowSize);
8280 }
8281
8282 WindowedObserver.prototype.next = function (value) {
8283 this.observer.onNext(value);
8284 this.received = ++this.received % this.observable.windowSize;
8285 this.received === 0 && (this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod));
8286 };
8287
8288 WindowedObserver.prototype.dispose = function () {
8289 this.observer = null;
8290 if (this.cancel) {
8291 this.cancel.dispose();
8292 this.cancel = null;
8293 }
8294 if (this.scheduleDisposable) {
8295 this.scheduleDisposable.dispose();
8296 this.scheduleDisposable = null;
8297 }
8298 __sub__.prototype.dispose.call(this);
8299 };
8300
8301 return WindowedObserver;
8302 }(AbstractObserver));
8303
8304 return WindowedObservable;
8305 }(Observable));
8306
8307 /**
8308 * Creates a sliding windowed observable based upon the window size.
8309 * @param {Number} windowSize The number of items in the window
8310 * @returns {Observable} A windowed observable based upon the window size.
8311 */
8312 ControlledObservable.prototype.windowed = function (windowSize) {
8313 return new WindowedObservable(this, windowSize);
8314 };
8315
8316 /**
8317 * Pipes the existing Observable sequence into a Node.js Stream.
8318 * @param {Stream} dest The destination Node.js stream.
8319 * @returns {Stream} The destination stream.
8320 */
8321 observableProto.pipe = function (dest) {
8322 var source = this.pausableBuffered();
8323
8324 function onDrain() {
8325 source.resume();
8326 }
8327
8328 dest.addListener('drain', onDrain);
8329
8330 source.subscribe(
8331 function (x) {
8332 !dest.write(String(x)) && source.pause();
8333 },
8334 function (err) {
8335 dest.emit('error', err);
8336 },
8337 function () {
8338 // Hack check because STDIO is not closable
8339 !dest._isStdio && dest.end();
8340 dest.removeListener('drain', onDrain);
8341 });
8342
8343 source.resume();
8344
8345 return dest;
8346 };
8347
8348 var MulticastObservable = (function (__super__) {
8349 inherits(MulticastObservable, __super__);
8350 function MulticastObservable(source, fn1, fn2) {
8351 this.source = source;
8352 this._fn1 = fn1;
8353 this._fn2 = fn2;
8354 __super__.call(this);
8355 }
8356
8357 MulticastObservable.prototype.subscribeCore = function (o) {
8358 var connectable = this.source.multicast(this._fn1());
8359 return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
8360 };
8361
8362 return MulticastObservable;
8363 }(ObservableBase));
8364
8365 /**
8366 * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
8367 * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
8368 * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
8369 *
8370 * @example
8371 * 1 - res = source.multicast(observable);
8372 * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
8373 *
8374 * @param {Function|Subject} subjectOrSubjectSelector
8375 * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
8376 * Or:
8377 * Subject to push source elements into.
8378 *
8379 * @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.
8380 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
8381 */
8382 observableProto.multicast = function (subjectOrSubjectSelector, selector) {
8383 return isFunction(subjectOrSubjectSelector) ?
8384 new MulticastObservable(this, subjectOrSubjectSelector, selector) :
8385 new ConnectableObservable(this, subjectOrSubjectSelector);
8386 };
8387
8388 /**
8389 * 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.
8390 * This operator is a specialization of Multicast using a regular Subject.
8391 *
8392 * @example
8393 * var resres = source.publish();
8394 * var res = source.publish(function (x) { return x; });
8395 *
8396 * @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.
8397 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
8398 */
8399 observableProto.publish = function (selector) {
8400 return selector && isFunction(selector) ?
8401 this.multicast(function () { return new Subject(); }, selector) :
8402 this.multicast(new Subject());
8403 };
8404
8405 /**
8406 * Returns an observable sequence that shares a single subscription to the underlying sequence.
8407 * 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.
8408 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
8409 */
8410 observableProto.share = function () {
8411 return this.publish().refCount();
8412 };
8413
8414 /**
8415 * 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.
8416 * This operator is a specialization of Multicast using a AsyncSubject.
8417 *
8418 * @example
8419 * var res = source.publishLast();
8420 * var res = source.publishLast(function (x) { return x; });
8421 *
8422 * @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.
8423 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
8424 */
8425 observableProto.publishLast = function (selector) {
8426 return selector && isFunction(selector) ?
8427 this.multicast(function () { return new AsyncSubject(); }, selector) :
8428 this.multicast(new AsyncSubject());
8429 };
8430
8431 /**
8432 * 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.
8433 * This operator is a specialization of Multicast using a BehaviorSubject.
8434 *
8435 * @example
8436 * var res = source.publishValue(42);
8437 * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
8438 *
8439 * @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.
8440 * @param {Mixed} initialValue Initial value received by observers upon subscription.
8441 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
8442 */
8443 observableProto.publishValue = function (initialValueOrSelector, initialValue) {
8444 return arguments.length === 2 ?
8445 this.multicast(function () {
8446 return new BehaviorSubject(initialValue);
8447 }, initialValueOrSelector) :
8448 this.multicast(new BehaviorSubject(initialValueOrSelector));
8449 };
8450
8451 /**
8452 * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
8453 * 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.
8454 * @param {Mixed} initialValue Initial value received by observers upon subscription.
8455 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
8456 */
8457 observableProto.shareValue = function (initialValue) {
8458 return this.publishValue(initialValue).refCount();
8459 };
8460
8461 /**
8462 * 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.
8463 * This operator is a specialization of Multicast using a ReplaySubject.
8464 *
8465 * @example
8466 * var res = source.replay(null, 3);
8467 * var res = source.replay(null, 3, 500);
8468 * var res = source.replay(null, 3, 500, scheduler);
8469 * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
8470 *
8471 * @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.
8472 * @param bufferSize [Optional] Maximum element count of the replay buffer.
8473 * @param windowSize [Optional] Maximum time length of the replay buffer.
8474 * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
8475 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
8476 */
8477 observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
8478 return selector && isFunction(selector) ?
8479 this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
8480 this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
8481 };
8482
8483 /**
8484 * 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.
8485 * 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.
8486 *
8487 * @example
8488 * var res = source.shareReplay(3);
8489 * var res = source.shareReplay(3, 500);
8490 * var res = source.shareReplay(3, 500, scheduler);
8491 *
8492
8493 * @param bufferSize [Optional] Maximum element count of the replay buffer.
8494 * @param window [Optional] Maximum time length of the replay buffer.
8495 * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
8496 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
8497 */
8498 observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
8499 return this.replay(null, bufferSize, windowSize, scheduler).refCount();
8500 };
8501
8502 var InnerSubscription = function (s, o) {
8503 this._s = s;
8504 this._o = o;
8505 };
8506
8507 InnerSubscription.prototype.dispose = function () {
8508 if (!this._s.isDisposed && this._o !== null) {
8509 var idx = this._s.observers.indexOf(this._o);
8510 this._s.observers.splice(idx, 1);
8511 this._o = null;
8512 }
8513 };
8514
8515 var RefCountObservable = (function (__super__) {
8516 inherits(RefCountObservable, __super__);
8517 function RefCountObservable(source) {
8518 this.source = source;
8519 this._count = 0;
8520 this._connectableSubscription = null;
8521 __super__.call(this);
8522 }
8523
8524 RefCountObservable.prototype.subscribeCore = function (o) {
8525 var subscription = this.source.subscribe(o);
8526 ++this._count === 1 && (this._connectableSubscription = this.source.connect());
8527 return new RefCountDisposable(this, subscription);
8528 };
8529
8530 function RefCountDisposable(p, s) {
8531 this._p = p;
8532 this._s = s;
8533 this.isDisposed = false;
8534 }
8535
8536 RefCountDisposable.prototype.dispose = function () {
8537 if (!this.isDisposed) {
8538 this.isDisposed = true;
8539 this._s.dispose();
8540 --this._p._count === 0 && this._p._connectableSubscription.dispose();
8541 }
8542 };
8543
8544 return RefCountObservable;
8545 }(ObservableBase));
8546
8547 var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
8548 inherits(ConnectableObservable, __super__);
8549 function ConnectableObservable(source, subject) {
8550 this.source = source;
8551 this._connection = null;
8552 this._source = source.asObservable();
8553 this._subject = subject;
8554 __super__.call(this);
8555 }
8556
8557 function ConnectDisposable(parent, subscription) {
8558 this._p = parent;
8559 this._s = subscription;
8560 }
8561
8562 ConnectDisposable.prototype.dispose = function () {
8563 if (this._s) {
8564 this._s.dispose();
8565 this._s = null;
8566 this._p._connection = null;
8567 }
8568 };
8569
8570 ConnectableObservable.prototype.connect = function () {
8571 if (!this._connection) {
8572 var subscription = this._source.subscribe(this._subject);
8573 this._connection = new ConnectDisposable(this, subscription);
8574 }
8575 return this._connection;
8576 };
8577
8578 ConnectableObservable.prototype._subscribe = function (o) {
8579 return this._subject.subscribe(o);
8580 };
8581
8582 ConnectableObservable.prototype.refCount = function () {
8583 return new RefCountObservable(this);
8584 };
8585
8586 return ConnectableObservable;
8587 }(Observable));
8588
8589 /**
8590 * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
8591 * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
8592 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
8593 */
8594 observableProto.singleInstance = function() {
8595 var source = this, hasObservable = false, observable;
8596
8597 function getObservable() {
8598 if (!hasObservable) {
8599 hasObservable = true;
8600 observable = source['finally'](function() { hasObservable = false; }).publish().refCount();
8601 }
8602 return observable;
8603 }
8604
8605 return new AnonymousObservable(function(o) {
8606 return getObservable().subscribe(o);
8607 });
8608 };
8609
8610 /**
8611 * Correlates the elements of two sequences based on overlapping durations.
8612 *
8613 * @param {Observable} right The right observable sequence to join elements for.
8614 * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
8615 * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
8616 * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
8617 * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
8618 */
8619 observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
8620 var left = this;
8621 return new AnonymousObservable(function (o) {
8622 var group = new CompositeDisposable();
8623 var leftDone = false, rightDone = false;
8624 var leftId = 0, rightId = 0;
8625 var leftMap = new Map(), rightMap = new Map();
8626 var handleError = function (e) { o.onError(e); };
8627
8628 group.add(left.subscribe(
8629 function (value) {
8630 var id = leftId++, md = new SingleAssignmentDisposable();
8631
8632 leftMap.set(id, value);
8633 group.add(md);
8634
8635 var duration = tryCatch(leftDurationSelector)(value);
8636 if (duration === errorObj) { return o.onError(duration.e); }
8637
8638 md.setDisposable(duration.take(1).subscribe(
8639 noop,
8640 handleError,
8641 function () {
8642 leftMap['delete'](id) && leftMap.size === 0 && leftDone && o.onCompleted();
8643 group.remove(md);
8644 }));
8645
8646 rightMap.forEach(function (v) {
8647 var result = tryCatch(resultSelector)(value, v);
8648 if (result === errorObj) { return o.onError(result.e); }
8649 o.onNext(result);
8650 });
8651 },
8652 handleError,
8653 function () {
8654 leftDone = true;
8655 (rightDone || leftMap.size === 0) && o.onCompleted();
8656 })
8657 );
8658
8659 group.add(right.subscribe(
8660 function (value) {
8661 var id = rightId++, md = new SingleAssignmentDisposable();
8662
8663 rightMap.set(id, value);
8664 group.add(md);
8665
8666 var duration = tryCatch(rightDurationSelector)(value);
8667 if (duration === errorObj) { return o.onError(duration.e); }
8668
8669 md.setDisposable(duration.take(1).subscribe(
8670 noop,
8671 handleError,
8672 function () {
8673 rightMap['delete'](id) && rightMap.size === 0 && rightDone && o.onCompleted();
8674 group.remove(md);
8675 }));
8676
8677 leftMap.forEach(function (v) {
8678 var result = tryCatch(resultSelector)(v, value);
8679 if (result === errorObj) { return o.onError(result.e); }
8680 o.onNext(result);
8681 });
8682 },
8683 handleError,
8684 function () {
8685 rightDone = true;
8686 (leftDone || rightMap.size === 0) && o.onCompleted();
8687 })
8688 );
8689 return group;
8690 }, left);
8691 };
8692
8693 /**
8694 * Correlates the elements of two sequences based on overlapping durations, and groups the results.
8695 *
8696 * @param {Observable} right The right observable sequence to join elements for.
8697 * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
8698 * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
8699 * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
8700 * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
8701 */
8702 observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
8703 var left = this;
8704 return new AnonymousObservable(function (o) {
8705 var group = new CompositeDisposable();
8706 var r = new RefCountDisposable(group);
8707 var leftMap = new Map(), rightMap = new Map();
8708 var leftId = 0, rightId = 0;
8709 var handleError = function (e) { return function (v) { v.onError(e); }; };
8710
8711 function handleError(e) { };
8712
8713 group.add(left.subscribe(
8714 function (value) {
8715 var s = new Subject();
8716 var id = leftId++;
8717 leftMap.set(id, s);
8718
8719 var result = tryCatch(resultSelector)(value, addRef(s, r));
8720 if (result === errorObj) {
8721 leftMap.forEach(handleError(result.e));
8722 return o.onError(result.e);
8723 }
8724 o.onNext(result);
8725
8726 rightMap.forEach(function (v) { s.onNext(v); });
8727
8728 var md = new SingleAssignmentDisposable();
8729 group.add(md);
8730
8731 var duration = tryCatch(leftDurationSelector)(value);
8732 if (duration === errorObj) {
8733 leftMap.forEach(handleError(duration.e));
8734 return o.onError(duration.e);
8735 }
8736
8737 md.setDisposable(duration.take(1).subscribe(
8738 noop,
8739 function (e) {
8740 leftMap.forEach(handleError(e));
8741 o.onError(e);
8742 },
8743 function () {
8744 leftMap['delete'](id) && s.onCompleted();
8745 group.remove(md);
8746 }));
8747 },
8748 function (e) {
8749 leftMap.forEach(handleError(e));
8750 o.onError(e);
8751 },
8752 function () { o.onCompleted(); })
8753 );
8754
8755 group.add(right.subscribe(
8756 function (value) {
8757 var id = rightId++;
8758 rightMap.set(id, value);
8759
8760 var md = new SingleAssignmentDisposable();
8761 group.add(md);
8762
8763 var duration = tryCatch(rightDurationSelector)(value);
8764 if (duration === errorObj) {
8765 leftMap.forEach(handleError(duration.e));
8766 return o.onError(duration.e);
8767 }
8768
8769 md.setDisposable(duration.take(1).subscribe(
8770 noop,
8771 function (e) {
8772 leftMap.forEach(handleError(e));
8773 o.onError(e);
8774 },
8775 function () {
8776 rightMap['delete'](id);
8777 group.remove(md);
8778 }));
8779
8780 leftMap.forEach(function (v) { v.onNext(value); });
8781 },
8782 function (e) {
8783 leftMap.forEach(handleError(e));
8784 o.onError(e);
8785 })
8786 );
8787
8788 return r;
8789 }, left);
8790 };
8791
8792 function toArray(x) { return x.toArray(); }
8793
8794 /**
8795 * Projects each element of an observable sequence into zero or more buffers.
8796 * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
8797 * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
8798 * @returns {Observable} An observable sequence of windows.
8799 */
8800 observableProto.buffer = function () {
8801 return this.window.apply(this, arguments)
8802 .flatMap(toArray);
8803 };
8804
8805 /**
8806 * Projects each element of an observable sequence into zero or more windows.
8807 *
8808 * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
8809 * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
8810 * @returns {Observable} An observable sequence of windows.
8811 */
8812 observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
8813 if (arguments.length === 1 && typeof arguments[0] !== 'function') {
8814 return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
8815 }
8816 return typeof windowOpeningsOrClosingSelector === 'function' ?
8817 observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
8818 observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
8819 };
8820
8821 function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
8822 return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
8823 return win;
8824 });
8825 }
8826
8827 function observableWindowWithBoundaries(windowBoundaries) {
8828 var source = this;
8829 return new AnonymousObservable(function (observer) {
8830 var win = new Subject(),
8831 d = new CompositeDisposable(),
8832 r = new RefCountDisposable(d);
8833
8834 observer.onNext(addRef(win, r));
8835
8836 d.add(source.subscribe(function (x) {
8837 win.onNext(x);
8838 }, function (err) {
8839 win.onError(err);
8840 observer.onError(err);
8841 }, function () {
8842 win.onCompleted();
8843 observer.onCompleted();
8844 }));
8845
8846 isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
8847
8848 d.add(windowBoundaries.subscribe(function (w) {
8849 win.onCompleted();
8850 win = new Subject();
8851 observer.onNext(addRef(win, r));
8852 }, function (err) {
8853 win.onError(err);
8854 observer.onError(err);
8855 }, function () {
8856 win.onCompleted();
8857 observer.onCompleted();
8858 }));
8859
8860 return r;
8861 }, source);
8862 }
8863
8864 function observableWindowWithClosingSelector(windowClosingSelector) {
8865 var source = this;
8866 return new AnonymousObservable(function (observer) {
8867 var m = new SerialDisposable(),
8868 d = new CompositeDisposable(m),
8869 r = new RefCountDisposable(d),
8870 win = new Subject();
8871 observer.onNext(addRef(win, r));
8872 d.add(source.subscribe(function (x) {
8873 win.onNext(x);
8874 }, function (err) {
8875 win.onError(err);
8876 observer.onError(err);
8877 }, function () {
8878 win.onCompleted();
8879 observer.onCompleted();
8880 }));
8881
8882 function createWindowClose () {
8883 var windowClose;
8884 try {
8885 windowClose = windowClosingSelector();
8886 } catch (e) {
8887 observer.onError(e);
8888 return;
8889 }
8890
8891 isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
8892
8893 var m1 = new SingleAssignmentDisposable();
8894 m.setDisposable(m1);
8895 m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
8896 win.onError(err);
8897 observer.onError(err);
8898 }, function () {
8899 win.onCompleted();
8900 win = new Subject();
8901 observer.onNext(addRef(win, r));
8902 createWindowClose();
8903 }));
8904 }
8905
8906 createWindowClose();
8907 return r;
8908 }, source);
8909 }
8910
8911 var PairwiseObservable = (function (__super__) {
8912 inherits(PairwiseObservable, __super__);
8913 function PairwiseObservable(source) {
8914 this.source = source;
8915 __super__.call(this);
8916 }
8917
8918 PairwiseObservable.prototype.subscribeCore = function (o) {
8919 return this.source.subscribe(new PairwiseObserver(o));
8920 };
8921
8922 return PairwiseObservable;
8923 }(ObservableBase));
8924
8925 var PairwiseObserver = (function(__super__) {
8926 inherits(PairwiseObserver, __super__);
8927 function PairwiseObserver(o) {
8928 this._o = o;
8929 this._p = null;
8930 this._hp = false;
8931 }
8932
8933 PairwiseObserver.prototype.next = function (x) {
8934 if (this._hp) {
8935 this._o.onNext([this._p, x]);
8936 } else {
8937 this._hp = true;
8938 }
8939 this._p = x;
8940 };
8941 PairwiseObserver.prototype.error = function (err) { this._o.onError(err); };
8942 PairwiseObserver.prototype.completed = function () { this._o.onCompleted(); };
8943
8944 return PairwiseObserver;
8945 }(AbstractObserver));
8946
8947 /**
8948 * Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
8949 * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
8950 * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
8951 * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
8952 */
8953 observableProto.pairwise = function () {
8954 return new PairwiseObservable(this);
8955 };
8956
8957 /**
8958 * Returns two observables which partition the observations of the source by the given function.
8959 * The first will trigger observations for those values for which the predicate returns true.
8960 * The second will trigger observations for those values where the predicate returns false.
8961 * The predicate is executed once for each subscribed observer.
8962 * Both also propagate all error observations arising from the source and each completes
8963 * when the source completes.
8964 * @param {Function} predicate
8965 * The function to determine which output Observable will trigger a particular observation.
8966 * @returns {Array}
8967 * An array of observables. The first triggers when the predicate returns true,
8968 * and the second triggers when the predicate returns false.
8969 */
8970 observableProto.partition = function(predicate, thisArg) {
8971 var fn = bindCallback(predicate, thisArg, 3);
8972 return [
8973 this.filter(predicate, thisArg),
8974 this.filter(function (x, i, o) { return !fn(x, i, o); })
8975 ];
8976 };
8977
8978 var WhileEnumerable = (function(__super__) {
8979 inherits(WhileEnumerable, __super__);
8980 function WhileEnumerable(c, s) {
8981 this.c = c;
8982 this.s = s;
8983 }
8984 WhileEnumerable.prototype[$iterator$] = function () {
8985 var self = this;
8986 return {
8987 next: function () {
8988 return self.c() ?
8989 { done: false, value: self.s } :
8990 { done: true, value: void 0 };
8991 }
8992 };
8993 };
8994 return WhileEnumerable;
8995 }(Enumerable));
8996
8997 function enumerableWhile(condition, source) {
8998 return new WhileEnumerable(condition, source);
8999 }
9000
9001 /**
9002 * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
9003 * This operator allows for a fluent style of writing queries that use the same sequence multiple times.
9004 *
9005 * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
9006 * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
9007 */
9008 observableProto.letBind = observableProto['let'] = function (func) {
9009 return func(this);
9010 };
9011
9012 /**
9013 * Determines whether an observable collection contains values.
9014 *
9015 * @example
9016 * 1 - res = Rx.Observable.if(condition, obs1);
9017 * 2 - res = Rx.Observable.if(condition, obs1, obs2);
9018 * 3 - res = Rx.Observable.if(condition, obs1, scheduler);
9019 * @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
9020 * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
9021 * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
9022 * @returns {Observable} An observable sequence which is either the thenSource or elseSource.
9023 */
9024 Observable['if'] = function (condition, thenSource, elseSourceOrScheduler) {
9025 return observableDefer(function () {
9026 elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
9027
9028 isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
9029 isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
9030
9031 // Assume a scheduler for empty only
9032 typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
9033 return condition() ? thenSource : elseSourceOrScheduler;
9034 });
9035 };
9036
9037 /**
9038 * Concatenates the observable sequences obtained by running the specified result selector for each element in source.
9039 * There is an alias for this method called 'forIn' for browsers <IE9
9040 * @param {Array} sources An array of values to turn into an observable sequence.
9041 * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
9042 * @returns {Observable} An observable sequence from the concatenated observable sequences.
9043 */
9044 Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
9045 return enumerableOf(sources, resultSelector, thisArg).concat();
9046 };
9047
9048 /**
9049 * Repeats source as long as condition holds emulating a while loop.
9050 * There is an alias for this method called 'whileDo' for browsers <IE9
9051 *
9052 * @param {Function} condition The condition which determines if the source will be repeated.
9053 * @param {Observable} source The observable sequence that will be run if the condition function returns true.
9054 * @returns {Observable} An observable sequence which is repeated as long as the condition holds.
9055 */
9056 var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
9057 isPromise(source) && (source = observableFromPromise(source));
9058 return enumerableWhile(condition, source).concat();
9059 };
9060
9061 /**
9062 * Repeats source as long as condition holds emulating a do while loop.
9063 *
9064 * @param {Function} condition The condition which determines if the source will be repeated.
9065 * @param {Observable} source The observable sequence that will be run if the condition function returns true.
9066 * @returns {Observable} An observable sequence which is repeated as long as the condition holds.
9067 */
9068 observableProto.doWhile = function (condition) {
9069 return observableConcat([this, observableWhileDo(condition, this)]);
9070 };
9071
9072 /**
9073 * Uses selector to determine which source in sources to use.
9074 * @param {Function} selector The function which extracts the value for to test in a case statement.
9075 * @param {Array} sources A object which has keys which correspond to the case statement labels.
9076 * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
9077 *
9078 * @returns {Observable} An observable sequence which is determined by a case statement.
9079 */
9080 Observable['case'] = function (selector, sources, defaultSourceOrScheduler) {
9081 return observableDefer(function () {
9082 isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
9083 defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
9084
9085 isScheduler(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
9086
9087 var result = sources[selector()];
9088 isPromise(result) && (result = observableFromPromise(result));
9089
9090 return result || defaultSourceOrScheduler;
9091 });
9092 };
9093
9094 var ExpandObservable = (function(__super__) {
9095 inherits(ExpandObservable, __super__);
9096 function ExpandObservable(source, fn, scheduler) {
9097 this.source = source;
9098 this._fn = fn;
9099 this._scheduler = scheduler;
9100 __super__.call(this);
9101 }
9102
9103 function scheduleRecursive(args, recurse) {
9104 var state = args[0], self = args[1];
9105 var work;
9106 if (state.q.length > 0) {
9107 work = state.q.shift();
9108 } else {
9109 state.isAcquired = false;
9110 return;
9111 }
9112 var m1 = new SingleAssignmentDisposable();
9113 state.d.add(m1);
9114 m1.setDisposable(work.subscribe(new ExpandObserver(state, self, m1)));
9115 recurse([state, self]);
9116 }
9117
9118 ExpandObservable.prototype._ensureActive = function (state) {
9119 var isOwner = false;
9120 if (state.q.length > 0) {
9121 isOwner = !state.isAcquired;
9122 state.isAcquired = true;
9123 }
9124 isOwner && state.m.setDisposable(this._scheduler.scheduleRecursive([state, this], scheduleRecursive));
9125 };
9126
9127 ExpandObservable.prototype.subscribeCore = function (o) {
9128 var m = new SerialDisposable(),
9129 d = new CompositeDisposable(m),
9130 state = {
9131 q: [],
9132 m: m,
9133 d: d,
9134 activeCount: 0,
9135 isAcquired: false,
9136 o: o
9137 };
9138
9139 state.q.push(this.source);
9140 state.activeCount++;
9141 this._ensureActive(state);
9142 return d;
9143 };
9144
9145 return ExpandObservable;
9146 }(ObservableBase));
9147
9148 var ExpandObserver = (function(__super__) {
9149 inherits(ExpandObserver, __super__);
9150 function ExpandObserver(state, parent, m1) {
9151 this._s = state;
9152 this._p = parent;
9153 this._m1 = m1;
9154 __super__.call(this);
9155 }
9156
9157 ExpandObserver.prototype.next = function (x) {
9158 this._s.o.onNext(x);
9159 var result = tryCatch(this._p._fn)(x);
9160 if (result === errorObj) { return this._s.o.onError(result.e); }
9161 this._s.q.push(result);
9162 this._s.activeCount++;
9163 this._p._ensureActive(this._s);
9164 };
9165
9166 ExpandObserver.prototype.error = function (e) {
9167 this._s.o.onError(e);
9168 };
9169
9170 ExpandObserver.prototype.completed = function () {
9171 this._s.d.remove(this._m1);
9172 this._s.activeCount--;
9173 this._s.activeCount === 0 && this._s.o.onCompleted();
9174 };
9175
9176 return ExpandObserver;
9177 }(AbstractObserver));
9178
9179 /**
9180 * Expands an observable sequence by recursively invoking selector.
9181 *
9182 * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
9183 * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
9184 * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
9185 */
9186 observableProto.expand = function (selector, scheduler) {
9187 isScheduler(scheduler) || (scheduler = currentThreadScheduler);
9188 return new ExpandObservable(this, selector, scheduler);
9189 };
9190
9191 function argumentsToArray() {
9192 var len = arguments.length, args = new Array(len);
9193 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
9194 return args;
9195 }
9196
9197 var ForkJoinObservable = (function (__super__) {
9198 inherits(ForkJoinObservable, __super__);
9199 function ForkJoinObservable(sources, cb) {
9200 this._sources = sources;
9201 this._cb = cb;
9202 __super__.call(this);
9203 }
9204
9205 ForkJoinObservable.prototype.subscribeCore = function (o) {
9206 if (this._sources.length === 0) {
9207 o.onCompleted();
9208 return disposableEmpty;
9209 }
9210
9211 var count = this._sources.length;
9212 var state = {
9213 finished: false,
9214 hasResults: new Array(count),
9215 hasCompleted: new Array(count),
9216 results: new Array(count)
9217 };
9218
9219 var subscriptions = new CompositeDisposable();
9220 for (var i = 0, len = this._sources.length; i < len; i++) {
9221 var source = this._sources[i];
9222 isPromise(source) && (source = observableFromPromise(source));
9223 subscriptions.add(source.subscribe(new ForkJoinObserver(o, state, i, this._cb, subscriptions)));
9224 }
9225
9226 return subscriptions;
9227 };
9228
9229 return ForkJoinObservable;
9230 }(ObservableBase));
9231
9232 var ForkJoinObserver = (function(__super__) {
9233 inherits(ForkJoinObserver, __super__);
9234 function ForkJoinObserver(o, s, i, cb, subs) {
9235 this._o = o;
9236 this._s = s;
9237 this._i = i;
9238 this._cb = cb;
9239 this._subs = subs;
9240 __super__.call(this);
9241 }
9242
9243 ForkJoinObserver.prototype.next = function (x) {
9244 if (!this._s.finished) {
9245 this._s.hasResults[this._i] = true;
9246 this._s.results[this._i] = x;
9247 }
9248 };
9249
9250 ForkJoinObserver.prototype.error = function (e) {
9251 this._s.finished = true;
9252 this._o.onError(e);
9253 this._subs.dispose();
9254 };
9255
9256 ForkJoinObserver.prototype.completed = function () {
9257 if (!this._s.finished) {
9258 if (!this._s.hasResults[this._i]) {
9259 return this._o.onCompleted();
9260 }
9261 this._s.hasCompleted[this._i] = true;
9262 for (var i = 0; i < this._s.results.length; i++) {
9263 if (!this._s.hasCompleted[i]) { return; }
9264 }
9265 this._s.finished = true;
9266
9267 var res = tryCatch(this._cb).apply(null, this._s.results);
9268 if (res === errorObj) { return this._o.onError(res.e); }
9269
9270 this._o.onNext(res);
9271 this._o.onCompleted();
9272 }
9273 };
9274
9275 return ForkJoinObserver;
9276 }(AbstractObserver));
9277
9278 /**
9279 * Runs all observable sequences in parallel and collect their last elements.
9280 *
9281 * @example
9282 * 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
9283 * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
9284 * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
9285 */
9286 Observable.forkJoin = function () {
9287 var len = arguments.length, args = new Array(len);
9288 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
9289 var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
9290 Array.isArray(args[0]) && (args = args[0]);
9291 return new ForkJoinObservable(args, resultSelector);
9292 };
9293
9294 /**
9295 * Runs two observable sequences in parallel and combines their last elemenets.
9296 * @param {Observable} second Second observable sequence.
9297 * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
9298 * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
9299 */
9300 observableProto.forkJoin = function () {
9301 var len = arguments.length, args = new Array(len);
9302 for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
9303 if (Array.isArray(args[0])) {
9304 args[0].unshift(this);
9305 } else {
9306 args.unshift(this);
9307 }
9308 return Observable.forkJoin.apply(null, args);
9309 };
9310
9311 /**
9312 * Comonadic bind operator.
9313 * @param {Function} selector A transform function to apply to each element.
9314 * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
9315 * @returns {Observable} An observable sequence which results from the comonadic bind operation.
9316 */
9317 observableProto.manySelect = observableProto.extend = function (selector, scheduler) {
9318 isScheduler(scheduler) || (scheduler = Rx.Scheduler.immediate);
9319 var source = this;
9320 return observableDefer(function () {
9321 var chain;
9322
9323 return source
9324 .map(function (x) {
9325 var curr = new ChainObservable(x);
9326
9327 chain && chain.onNext(x);
9328 chain = curr;
9329
9330 return curr;
9331 })
9332 .tap(
9333 noop,
9334 function (e) { chain && chain.onError(e); },
9335 function () { chain && chain.onCompleted(); }
9336 )
9337 .observeOn(scheduler)
9338 .map(selector);
9339 }, source);
9340 };
9341
9342 var ChainObservable = (function (__super__) {
9343 inherits(ChainObservable, __super__);
9344 function ChainObservable(head) {
9345 __super__.call(this);
9346 this.head = head;
9347 this.tail = new AsyncSubject();
9348 }
9349
9350 addProperties(ChainObservable.prototype, Observer, {
9351 _subscribe: function (o) {
9352 var g = new CompositeDisposable();
9353 g.add(currentThreadScheduler.schedule(this, function (_, self) {
9354 o.onNext(self.head);
9355 g.add(self.tail.mergeAll().subscribe(o));
9356 }));
9357
9358 return g;
9359 },
9360 onCompleted: function () {
9361 this.onNext(Observable.empty());
9362 },
9363 onError: function (e) {
9364 this.onNext(Observable['throw'](e));
9365 },
9366 onNext: function (v) {
9367 this.tail.onNext(v);
9368 this.tail.onCompleted();
9369 }
9370 });
9371
9372 return ChainObservable;
9373
9374 }(Observable));
9375
9376 var Map = root.Map || (function () {
9377 function Map() {
9378 this.size = 0;
9379 this._values = [];
9380 this._keys = [];
9381 }
9382
9383 Map.prototype['delete'] = function (key) {
9384 var i = this._keys.indexOf(key);
9385 if (i === -1) { return false; }
9386 this._values.splice(i, 1);
9387 this._keys.splice(i, 1);
9388 this.size--;
9389 return true;
9390 };
9391
9392 Map.prototype.get = function (key) {
9393 var i = this._keys.indexOf(key);
9394 return i === -1 ? undefined : this._values[i];
9395 };
9396
9397 Map.prototype.set = function (key, value) {
9398 var i = this._keys.indexOf(key);
9399 if (i === -1) {
9400 this._keys.push(key);
9401 this._values.push(value);
9402 this.size++;
9403 } else {
9404 this._values[i] = value;
9405 }
9406 return this;
9407 };
9408
9409 Map.prototype.forEach = function (cb, thisArg) {
9410 for (var i = 0; i < this.size; i++) {
9411 cb.call(thisArg, this._values[i], this._keys[i]);
9412 }
9413 };
9414
9415 return Map;
9416 }());
9417
9418 /**
9419 * @constructor
9420 * Represents a join pattern over observable sequences.
9421 */
9422 function Pattern(patterns) {
9423 this.patterns = patterns;
9424 }
9425
9426 /**
9427 * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
9428 * @param other Observable sequence to match in addition to the current pattern.
9429 * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
9430 */
9431 Pattern.prototype.and = function (other) {
9432 return new Pattern(this.patterns.concat(other));
9433 };
9434
9435 /**
9436 * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
9437 * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
9438 * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
9439 */
9440 Pattern.prototype.thenDo = function (selector) {
9441 return new Plan(this, selector);
9442 };
9443
9444 function Plan(expression, selector) {
9445 this.expression = expression;
9446 this.selector = selector;
9447 }
9448
9449 function handleOnError(o) { return function (e) { o.onError(e); }; }
9450 function handleOnNext(self, observer) {
9451 return function onNext () {
9452 var result = tryCatch(self.selector).apply(self, arguments);
9453 if (result === errorObj) { return observer.onError(result.e); }
9454 observer.onNext(result);
9455 };
9456 }
9457
9458 Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
9459 var joinObservers = [], errHandler = handleOnError(observer);
9460 for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
9461 joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], errHandler));
9462 }
9463 var activePlan = new ActivePlan(joinObservers, handleOnNext(this, observer), function () {
9464 for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
9465 joinObservers[j].removeActivePlan(activePlan);
9466 }
9467 deactivate(activePlan);
9468 });
9469 for (i = 0, len = joinObservers.length; i < len; i++) {
9470 joinObservers[i].addActivePlan(activePlan);
9471 }
9472 return activePlan;
9473 };
9474
9475 function planCreateObserver(externalSubscriptions, observable, onError) {
9476 var entry = externalSubscriptions.get(observable);
9477 if (!entry) {
9478 var observer = new JoinObserver(observable, onError);
9479 externalSubscriptions.set(observable, observer);
9480 return observer;
9481 }
9482 return entry;
9483 }
9484
9485 function ActivePlan(joinObserverArray, onNext, onCompleted) {
9486 this.joinObserverArray = joinObserverArray;
9487 this.onNext = onNext;
9488 this.onCompleted = onCompleted;
9489 this.joinObservers = new Map();
9490 for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
9491 var joinObserver = this.joinObserverArray[i];
9492 this.joinObservers.set(joinObserver, joinObserver);
9493 }
9494 }
9495
9496 ActivePlan.prototype.dequeue = function () {
9497 this.joinObservers.forEach(function (v) { v.queue.shift(); });
9498 };
9499
9500 ActivePlan.prototype.match = function () {
9501 var i, len, hasValues = true;
9502 for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
9503 if (this.joinObserverArray[i].queue.length === 0) {
9504 hasValues = false;
9505 break;
9506 }
9507 }
9508 if (hasValues) {
9509 var firstValues = [],
9510 isCompleted = false;
9511 for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
9512 firstValues.push(this.joinObserverArray[i].queue[0]);
9513 this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
9514 }
9515 if (isCompleted) {
9516 this.onCompleted();
9517 } else {
9518 this.dequeue();
9519 var values = [];
9520 for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
9521 values.push(firstValues[i].value);
9522 }
9523 this.onNext.apply(this, values);
9524 }
9525 }
9526 };
9527
9528 var JoinObserver = (function (__super__) {
9529 inherits(JoinObserver, __super__);
9530
9531 function JoinObserver(source, onError) {
9532 __super__.call(this);
9533 this.source = source;
9534 this.onError = onError;
9535 this.queue = [];
9536 this.activePlans = [];
9537 this.subscription = new SingleAssignmentDisposable();
9538 this.isDisposed = false;
9539 }
9540
9541 var JoinObserverPrototype = JoinObserver.prototype;
9542
9543 JoinObserverPrototype.next = function (notification) {
9544 if (!this.isDisposed) {
9545 if (notification.kind === 'E') {
9546 return this.onError(notification.error);
9547 }
9548 this.queue.push(notification);
9549 var activePlans = this.activePlans.slice(0);
9550 for (var i = 0, len = activePlans.length; i < len; i++) {
9551 activePlans[i].match();
9552 }
9553 }
9554 };
9555
9556 JoinObserverPrototype.error = noop;
9557 JoinObserverPrototype.completed = noop;
9558
9559 JoinObserverPrototype.addActivePlan = function (activePlan) {
9560 this.activePlans.push(activePlan);
9561 };
9562
9563 JoinObserverPrototype.subscribe = function () {
9564 this.subscription.setDisposable(this.source.materialize().subscribe(this));
9565 };
9566
9567 JoinObserverPrototype.removeActivePlan = function (activePlan) {
9568 this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
9569 this.activePlans.length === 0 && this.dispose();
9570 };
9571
9572 JoinObserverPrototype.dispose = function () {
9573 __super__.prototype.dispose.call(this);
9574 if (!this.isDisposed) {
9575 this.isDisposed = true;
9576 this.subscription.dispose();
9577 }
9578 };
9579
9580 return JoinObserver;
9581 } (AbstractObserver));
9582
9583 /**
9584 * Creates a pattern that matches when both observable sequences have an available value.
9585 *
9586 * @param right Observable sequence to match with the current sequence.
9587 * @return {Pattern} Pattern object that matches when both observable sequences have an available value.
9588 */
9589 observableProto.and = function (right) {
9590 return new Pattern([this, right]);
9591 };
9592
9593 /**
9594 * Matches when the observable sequence has an available value and projects the value.
9595 *
9596 * @param {Function} selector Selector that will be invoked for values in the source sequence.
9597 * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
9598 */
9599 observableProto.thenDo = function (selector) {
9600 return new Pattern([this]).thenDo(selector);
9601 };
9602
9603 /**
9604 * Joins together the results from several patterns.
9605 *
9606 * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
9607 * @returns {Observable} Observable sequence with the results form matching several patterns.
9608 */
9609 Observable.when = function () {
9610 var len = arguments.length, plans;
9611 if (Array.isArray(arguments[0])) {
9612 plans = arguments[0];
9613 } else {
9614 plans = new Array(len);
9615 for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
9616 }
9617 return new AnonymousObservable(function (o) {
9618 var activePlans = [],
9619 externalSubscriptions = new Map();
9620 var outObserver = observerCreate(
9621 function (x) { o.onNext(x); },
9622 function (err) {
9623 externalSubscriptions.forEach(function (v) { v.onError(err); });
9624 o.onError(err);
9625 },
9626 function (x) { o.onCompleted(); }
9627 );
9628 try {
9629 for (var i = 0, len = plans.length; i < len; i++) {
9630 activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
9631 var idx = activePlans.indexOf(activePlan);
9632 activePlans.splice(idx, 1);
9633 activePlans.length === 0 && o.onCompleted();
9634 }));
9635 }
9636 } catch (e) {
9637 observableThrow(e).subscribe(o);
9638 }
9639 var group = new CompositeDisposable();
9640 externalSubscriptions.forEach(function (joinObserver) {
9641 joinObserver.subscribe();
9642 group.add(joinObserver);
9643 });
9644
9645 return group;
9646 });
9647 };
9648
9649 var TimerObservable = (function(__super__) {
9650 inherits(TimerObservable, __super__);
9651 function TimerObservable(dt, s) {
9652 this._dt = dt;
9653 this._s = s;
9654 __super__.call(this);
9655 }
9656
9657 TimerObservable.prototype.subscribeCore = function (o) {
9658 return this._s.scheduleFuture(o, this._dt, scheduleMethod);
9659 };
9660
9661 function scheduleMethod(s, o) {
9662 o.onNext(0);
9663 o.onCompleted();
9664 }
9665
9666 return TimerObservable;
9667 }(ObservableBase));
9668
9669 function _observableTimer(dueTime, scheduler) {
9670 return new TimerObservable(dueTime, scheduler);
9671 }
9672
9673 function observableTimerDateAndPeriod(dueTime, period, scheduler) {
9674 return new AnonymousObservable(function (observer) {
9675 var d = dueTime, p = normalizeTime(period);
9676 return scheduler.scheduleRecursiveFuture(0, d, function (count, self) {
9677 if (p > 0) {
9678 var now = scheduler.now();
9679 d = new Date(d.getTime() + p);
9680 d.getTime() <= now && (d = new Date(now + p));
9681 }
9682 observer.onNext(count);
9683 self(count + 1, new Date(d));
9684 });
9685 });
9686 }
9687
9688 function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
9689 return dueTime === period ?
9690 new AnonymousObservable(function (observer) {
9691 return scheduler.schedulePeriodic(0, period, function (count) {
9692 observer.onNext(count);
9693 return count + 1;
9694 });
9695 }) :
9696 observableDefer(function () {
9697 return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler);
9698 });
9699 }
9700
9701 /**
9702 * Returns an observable sequence that produces a value after each period.
9703 *
9704 * @example
9705 * 1 - res = Rx.Observable.interval(1000);
9706 * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
9707 *
9708 * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
9709 * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
9710 * @returns {Observable} An observable sequence that produces a value after each period.
9711 */
9712 var observableinterval = Observable.interval = function (period, scheduler) {
9713 return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler);
9714 };
9715
9716 /**
9717 * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
9718 * @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.
9719 * @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.
9720 * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
9721 * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
9722 */
9723 var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
9724 var period;
9725 isScheduler(scheduler) || (scheduler = defaultScheduler);
9726 if (periodOrScheduler != null && typeof periodOrScheduler === 'number') {
9727 period = periodOrScheduler;
9728 } else if (isScheduler(periodOrScheduler)) {
9729 scheduler = periodOrScheduler;
9730 }
9731 if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) {
9732 return _observableTimer(dueTime, scheduler);
9733 }
9734 if (dueTime instanceof Date && period !== undefined) {
9735 return observableTimerDateAndPeriod(dueTime.getTime(), periodOrScheduler, scheduler);
9736 }
9737 return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
9738 };
9739
9740 function observableDelayRelative(source, dueTime, scheduler) {
9741 return new AnonymousObservable(function (o) {
9742 var active = false,
9743 cancelable = new SerialDisposable(),
9744 exception = null,
9745 q = [],
9746 running = false,
9747 subscription;
9748 subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
9749 var d, shouldRun;
9750 if (notification.value.kind === 'E') {
9751 q = [];
9752 q.push(notification);
9753 exception = notification.value.error;
9754 shouldRun = !running;
9755 } else {
9756 q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
9757 shouldRun = !active;
9758 active = true;
9759 }
9760 if (shouldRun) {
9761 if (exception !== null) {
9762 o.onError(exception);
9763 } else {
9764 d = new SingleAssignmentDisposable();
9765 cancelable.setDisposable(d);
9766 d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) {
9767 var e, recurseDueTime, result, shouldRecurse;
9768 if (exception !== null) {
9769 return;
9770 }
9771 running = true;
9772 do {
9773 result = null;
9774 if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
9775 result = q.shift().value;
9776 }
9777 if (result !== null) {
9778 result.accept(o);
9779 }
9780 } while (result !== null);
9781 shouldRecurse = false;
9782 recurseDueTime = 0;
9783 if (q.length > 0) {
9784 shouldRecurse = true;
9785 recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
9786 } else {
9787 active = false;
9788 }
9789 e = exception;
9790 running = false;
9791 if (e !== null) {
9792 o.onError(e);
9793 } else if (shouldRecurse) {
9794 self(null, recurseDueTime);
9795 }
9796 }));
9797 }
9798 }
9799 });
9800 return new BinaryDisposable(subscription, cancelable);
9801 }, source);
9802 }
9803
9804 function observableDelayAbsolute(source, dueTime, scheduler) {
9805 return observableDefer(function () {
9806 return observableDelayRelative(source, dueTime - scheduler.now(), scheduler);
9807 });
9808 }
9809
9810 function delayWithSelector(source, subscriptionDelay, delayDurationSelector) {
9811 var subDelay, selector;
9812 if (isFunction(subscriptionDelay)) {
9813 selector = subscriptionDelay;
9814 } else {
9815 subDelay = subscriptionDelay;
9816 selector = delayDurationSelector;
9817 }
9818 return new AnonymousObservable(function (o) {
9819 var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
9820
9821 function start() {
9822 subscription.setDisposable(source.subscribe(
9823 function (x) {
9824 var delay = tryCatch(selector)(x);
9825 if (delay === errorObj) { return o.onError(delay.e); }
9826 var d = new SingleAssignmentDisposable();
9827 delays.add(d);
9828 d.setDisposable(delay.subscribe(
9829 function () {
9830 o.onNext(x);
9831 delays.remove(d);
9832 done();
9833 },
9834 function (e) { o.onError(e); },
9835 function () {
9836 o.onNext(x);
9837 delays.remove(d);
9838 done();
9839 }
9840 ));
9841 },
9842 function (e) { o.onError(e); },
9843 function () {
9844 atEnd = true;
9845 subscription.dispose();
9846 done();
9847 }
9848 ));
9849 }
9850
9851 function done () {
9852 atEnd && delays.length === 0 && o.onCompleted();
9853 }
9854
9855 if (!subDelay) {
9856 start();
9857 } else {
9858 subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start));
9859 }
9860
9861 return new BinaryDisposable(subscription, delays);
9862 }, this);
9863 }
9864
9865 /**
9866 * Time shifts the observable sequence by dueTime.
9867 * The relative time intervals between the values are preserved.
9868 *
9869 * @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.
9870 * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
9871 * @returns {Observable} Time-shifted sequence.
9872 */
9873 observableProto.delay = function () {
9874 var firstArg = arguments[0];
9875 if (typeof firstArg === 'number' || firstArg instanceof Date) {
9876 var dueTime = firstArg, scheduler = arguments[1];
9877 isScheduler(scheduler) || (scheduler = defaultScheduler);
9878 return dueTime instanceof Date ?
9879 observableDelayAbsolute(this, dueTime, scheduler) :
9880 observableDelayRelative(this, dueTime, scheduler);
9881 } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
9882 return delayWithSelector(this, firstArg, arguments[1]);
9883 } else {
9884 throw new Error('Invalid arguments');
9885 }
9886 };
9887
9888 var DebounceObservable = (function (__super__) {
9889 inherits(DebounceObservable, __super__);
9890 function DebounceObservable(source, dt, s) {
9891 isScheduler(s) || (s = defaultScheduler);
9892 this.source = source;
9893 this._dt = dt;
9894 this._s = s;
9895 __super__.call(this);
9896 }
9897
9898 DebounceObservable.prototype.subscribeCore = function (o) {
9899 var cancelable = new SerialDisposable();
9900 return new BinaryDisposable(
9901 this.source.subscribe(new DebounceObserver(o, this.source, this._dt, this._s, cancelable)),
9902 cancelable);
9903 };
9904
9905 return DebounceObservable;
9906 }(ObservableBase));
9907
9908 var DebounceObserver = (function (__super__) {
9909 inherits(DebounceObserver, __super__);
9910 function DebounceObserver(observer, source, dueTime, scheduler, cancelable) {
9911 this._o = observer;
9912 this._s = source;
9913 this._d = dueTime;
9914 this._scheduler = scheduler;
9915 this._c = cancelable;
9916 this._v = null;
9917 this._hv = false;
9918 this._id = 0;
9919 __super__.call(this);
9920 }
9921
9922 DebounceObserver.prototype.next = function (x) {
9923 this._hv = true;
9924 this._v = x;
9925 var currentId = ++this._id, d = new SingleAssignmentDisposable();
9926 this._c.setDisposable(d);
9927 d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) {
9928 self._hv && self._id === currentId && self._o.onNext(x);
9929 self._hv = false;
9930 }));
9931 };
9932
9933 DebounceObserver.prototype.error = function (e) {
9934 this._c.dispose();
9935 this._o.onError(e);
9936 this._hv = false;
9937 this._id++;
9938 };
9939
9940 DebounceObserver.prototype.completed = function () {
9941 this._c.dispose();
9942 this._hv && this._o.onNext(this._v);
9943 this._o.onCompleted();
9944 this._hv = false;
9945 this._id++;
9946 };
9947
9948 return DebounceObserver;
9949 }(AbstractObserver));
9950
9951 function debounceWithSelector(source, durationSelector) {
9952 return new AnonymousObservable(function (o) {
9953 var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
9954 var subscription = source.subscribe(
9955 function (x) {
9956 var throttle = tryCatch(durationSelector)(x);
9957 if (throttle === errorObj) { return o.onError(throttle.e); }
9958
9959 isPromise(throttle) && (throttle = observableFromPromise(throttle));
9960
9961 hasValue = true;
9962 value = x;
9963 id++;
9964 var currentid = id, d = new SingleAssignmentDisposable();
9965 cancelable.setDisposable(d);
9966 d.setDisposable(throttle.subscribe(
9967 function () {
9968 hasValue && id === currentid && o.onNext(value);
9969 hasValue = false;
9970 d.dispose();
9971 },
9972 function (e) { o.onError(e); },
9973 function () {
9974 hasValue && id === currentid && o.onNext(value);
9975 hasValue = false;
9976 d.dispose();
9977 }
9978 ));
9979 },
9980 function (e) {
9981 cancelable.dispose();
9982 o.onError(e);
9983 hasValue = false;
9984 id++;
9985 },
9986 function () {
9987 cancelable.dispose();
9988 hasValue && o.onNext(value);
9989 o.onCompleted();
9990 hasValue = false;
9991 id++;
9992 }
9993 );
9994 return new BinaryDisposable(subscription, cancelable);
9995 }, source);
9996 }
9997
9998 observableProto.debounce = function () {
9999 if (isFunction (arguments[0])) {
10000 return debounceWithSelector(this, arguments[0]);
10001 } else if (typeof arguments[0] === 'number') {
10002 return new DebounceObservable(this, arguments[0], arguments[1]);
10003 } else {
10004 throw new Error('Invalid arguments');
10005 }
10006 };
10007
10008 /**
10009 * Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
10010 * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
10011 * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
10012 * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
10013 * @returns {Observable} An observable sequence of windows.
10014 */
10015 observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
10016 var source = this, timeShift;
10017 timeShiftOrScheduler == null && (timeShift = timeSpan);
10018 isScheduler(scheduler) || (scheduler = defaultScheduler);
10019 if (typeof timeShiftOrScheduler === 'number') {
10020 timeShift = timeShiftOrScheduler;
10021 } else if (isScheduler(timeShiftOrScheduler)) {
10022 timeShift = timeSpan;
10023 scheduler = timeShiftOrScheduler;
10024 }
10025 return new AnonymousObservable(function (observer) {
10026 var groupDisposable,
10027 nextShift = timeShift,
10028 nextSpan = timeSpan,
10029 q = [],
10030 refCountDisposable,
10031 timerD = new SerialDisposable(),
10032 totalTime = 0;
10033 groupDisposable = new CompositeDisposable(timerD),
10034 refCountDisposable = new RefCountDisposable(groupDisposable);
10035
10036 function createTimer () {
10037 var m = new SingleAssignmentDisposable(),
10038 isSpan = false,
10039 isShift = false;
10040 timerD.setDisposable(m);
10041 if (nextSpan === nextShift) {
10042 isSpan = true;
10043 isShift = true;
10044 } else if (nextSpan < nextShift) {
10045 isSpan = true;
10046 } else {
10047 isShift = true;
10048 }
10049 var newTotalTime = isSpan ? nextSpan : nextShift,
10050 ts = newTotalTime - totalTime;
10051 totalTime = newTotalTime;
10052 if (isSpan) {
10053 nextSpan += timeShift;
10054 }
10055 if (isShift) {
10056 nextShift += timeShift;
10057 }
10058 m.setDisposable(scheduler.scheduleFuture(null, ts, function () {
10059 if (isShift) {
10060 var s = new Subject();
10061 q.push(s);
10062 observer.onNext(addRef(s, refCountDisposable));
10063 }
10064 isSpan && q.shift().onCompleted();
10065 createTimer();
10066 }));
10067 };
10068 q.push(new Subject());
10069 observer.onNext(addRef(q[0], refCountDisposable));
10070 createTimer();
10071 groupDisposable.add(source.subscribe(
10072 function (x) {
10073 for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
10074 },
10075 function (e) {
10076 for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
10077 observer.onError(e);
10078 },
10079 function () {
10080 for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
10081 observer.onCompleted();
10082 }
10083 ));
10084 return refCountDisposable;
10085 }, source);
10086 };
10087
10088 /**
10089 * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
10090 * @param {Number} timeSpan Maximum time length of a window.
10091 * @param {Number} count Maximum element count of a window.
10092 * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
10093 * @returns {Observable} An observable sequence of windows.
10094 */
10095 observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
10096 var source = this;
10097 isScheduler(scheduler) || (scheduler = defaultScheduler);
10098 return new AnonymousObservable(function (observer) {
10099 var timerD = new SerialDisposable(),
10100 groupDisposable = new CompositeDisposable(timerD),
10101 refCountDisposable = new RefCountDisposable(groupDisposable),
10102 n = 0,
10103 windowId = 0,
10104 s = new Subject();
10105
10106 function createTimer(id) {
10107 var m = new SingleAssignmentDisposable();
10108 timerD.setDisposable(m);
10109 m.setDisposable(scheduler.scheduleFuture(null, timeSpan, function () {
10110 if (id !== windowId) { return; }
10111 n = 0;
10112 var newId = ++windowId;
10113 s.onCompleted();
10114 s = new Subject();
10115 observer.onNext(addRef(s, refCountDisposable));
10116 createTimer(newId);
10117 }));
10118 }
10119
10120 observer.onNext(addRef(s, refCountDisposable));
10121 createTimer(0);
10122
10123 groupDisposable.add(source.subscribe(
10124 function (x) {
10125 var newId = 0, newWindow = false;
10126 s.onNext(x);
10127 if (++n === count) {
10128 newWindow = true;
10129 n = 0;
10130 newId = ++windowId;
10131 s.onCompleted();
10132 s = new Subject();
10133 observer.onNext(addRef(s, refCountDisposable));
10134 }
10135 newWindow && createTimer(newId);
10136 },
10137 function (e) {
10138 s.onError(e);
10139 observer.onError(e);
10140 }, function () {
10141 s.onCompleted();
10142 observer.onCompleted();
10143 }
10144 ));
10145 return refCountDisposable;
10146 }, source);
10147 };
10148
10149 function toArray(x) { return x.toArray(); }
10150
10151 /**
10152 * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
10153 * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
10154 * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
10155 * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
10156 * @returns {Observable} An observable sequence of buffers.
10157 */
10158 observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
10159 return this.windowWithTime(timeSpan, timeShiftOrScheduler, scheduler).flatMap(toArray);
10160 };
10161
10162 function toArray(x) { return x.toArray(); }
10163
10164 /**
10165 * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
10166 * @param {Number} timeSpan Maximum time length of a buffer.
10167 * @param {Number} count Maximum element count of a buffer.
10168 * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
10169 * @returns {Observable} An observable sequence of buffers.
10170 */
10171 observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
10172 return this.windowWithTimeOrCount(timeSpan, count, scheduler).flatMap(toArray);
10173 };
10174
10175 var TimeIntervalObservable = (function (__super__) {
10176 inherits(TimeIntervalObservable, __super__);
10177 function TimeIntervalObservable(source, s) {
10178 this.source = source;
10179 this._s = s;
10180 __super__.call(this);
10181 }
10182
10183 TimeIntervalObservable.prototype.subscribeCore = function (o) {
10184 return this.source.subscribe(new TimeIntervalObserver(o, this._s));
10185 };
10186
10187 return TimeIntervalObservable;
10188 }(ObservableBase));
10189
10190 var TimeIntervalObserver = (function (__super__) {
10191 inherits(TimeIntervalObserver, __super__);
10192
10193 function TimeIntervalObserver(o, s) {
10194 this._o = o;
10195 this._s = s;
10196 this._l = s.now();
10197 __super__.call(this);
10198 }
10199
10200 TimeIntervalObserver.prototype.next = function (x) {
10201 var now = this._s.now(), span = now - this._l;
10202 this._l = now;
10203 this._o.onNext({ value: x, interval: span });
10204 };
10205 TimeIntervalObserver.prototype.error = function (e) { this._o.onError(e); };
10206 TimeIntervalObserver.prototype.completed = function () { this._o.onCompleted(); };
10207
10208 return TimeIntervalObserver;
10209 }(AbstractObserver));
10210
10211 /**
10212 * Records the time interval between consecutive values in an observable sequence.
10213 *
10214 * @example
10215 * 1 - res = source.timeInterval();
10216 * 2 - res = source.timeInterval(Rx.Scheduler.timeout);
10217 *
10218 * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
10219 * @returns {Observable} An observable sequence with time interval information on values.
10220 */
10221 observableProto.timeInterval = function (scheduler) {
10222 isScheduler(scheduler) || (scheduler = defaultScheduler);
10223 return new TimeIntervalObservable(this, scheduler);
10224 };
10225
10226 var TimestampObservable = (function (__super__) {
10227 inherits(TimestampObservable, __super__);
10228 function TimestampObservable(source, s) {
10229 this.source = source;
10230 this._s = s;
10231 __super__.call(this);
10232 }
10233
10234 TimestampObservable.prototype.subscribeCore = function (o) {
10235 return this.source.subscribe(new TimestampObserver(o, this._s));
10236 };
10237
10238 return TimestampObservable;
10239 }(ObservableBase));
10240
10241 var TimestampObserver = (function (__super__) {
10242 inherits(TimestampObserver, __super__);
10243 function TimestampObserver(o, s) {
10244 this._o = o;
10245 this._s = s;
10246 __super__.call(this);
10247 }
10248
10249 TimestampObserver.prototype.next = function (x) {
10250 this._o.onNext({ value: x, timestamp: this._s.now() });
10251 };
10252
10253 TimestampObserver.prototype.error = function (e) {
10254 this._o.onError(e);
10255 };
10256
10257 TimestampObserver.prototype.completed = function () {
10258 this._o.onCompleted();
10259 };
10260
10261 return TimestampObserver;
10262 }(AbstractObserver));
10263
10264 /**
10265 * Records the timestamp for each value in an observable sequence.
10266 *
10267 * @example
10268 * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
10269 * 2 - res = source.timestamp(Rx.Scheduler.default);
10270 *
10271 * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used.
10272 * @returns {Observable} An observable sequence with timestamp information on values.
10273 */
10274 observableProto.timestamp = function (scheduler) {
10275 isScheduler(scheduler) || (scheduler = defaultScheduler);
10276 return new TimestampObservable(this, scheduler);
10277 };
10278
10279 function sampleObservable(source, sampler) {
10280 return new AnonymousObservable(function (o) {
10281 var atEnd = false, value, hasValue = false;
10282
10283 function sampleSubscribe() {
10284 if (hasValue) {
10285 hasValue = false;
10286 o.onNext(value);
10287 }
10288 atEnd && o.onCompleted();
10289 }
10290
10291 var sourceSubscription = new SingleAssignmentDisposable();
10292 sourceSubscription.setDisposable(source.subscribe(
10293 function (newValue) {
10294 hasValue = true;
10295 value = newValue;
10296 },
10297 function (e) { o.onError(e); },
10298 function () {
10299 atEnd = true;
10300 sourceSubscription.dispose();
10301 }
10302 ));
10303
10304 return new BinaryDisposable(
10305 sourceSubscription,
10306 sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe)
10307 );
10308 }, source);
10309 }
10310
10311 /**
10312 * Samples the observable sequence at each interval.
10313 *
10314 * @example
10315 * 1 - res = source.sample(sampleObservable); // Sampler tick sequence
10316 * 2 - res = source.sample(5000); // 5 seconds
10317 * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
10318 *
10319 * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
10320 * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
10321 * @returns {Observable} Sampled observable sequence.
10322 */
10323 observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
10324 isScheduler(scheduler) || (scheduler = defaultScheduler);
10325 return typeof intervalOrSampler === 'number' ?
10326 sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
10327 sampleObservable(this, intervalOrSampler);
10328 };
10329
10330 var TimeoutError = Rx.TimeoutError = function(message) {
10331 this.message = message || 'Timeout has occurred';
10332 this.name = 'TimeoutError';
10333 Error.call(this);
10334 };
10335 TimeoutError.prototype = Object.create(Error.prototype);
10336
10337 function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) {
10338 if (isFunction(firstTimeout)) {
10339 other = timeoutDurationSelector;
10340 timeoutDurationSelector = firstTimeout;
10341 firstTimeout = observableNever();
10342 }
10343 Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
10344 return new AnonymousObservable(function (o) {
10345 var subscription = new SerialDisposable(),
10346 timer = new SerialDisposable(),
10347 original = new SingleAssignmentDisposable();
10348
10349 subscription.setDisposable(original);
10350
10351 var id = 0, switched = false;
10352
10353 function setTimer(timeout) {
10354 var myId = id, d = new SingleAssignmentDisposable();
10355
10356 function timerWins() {
10357 switched = (myId === id);
10358 return switched;
10359 }
10360
10361 timer.setDisposable(d);
10362 d.setDisposable(timeout.subscribe(function () {
10363 timerWins() && subscription.setDisposable(other.subscribe(o));
10364 d.dispose();
10365 }, function (e) {
10366 timerWins() && o.onError(e);
10367 }, function () {
10368 timerWins() && subscription.setDisposable(other.subscribe(o));
10369 }));
10370 };
10371
10372 setTimer(firstTimeout);
10373
10374 function oWins() {
10375 var res = !switched;
10376 if (res) { id++; }
10377 return res;
10378 }
10379
10380 original.setDisposable(source.subscribe(function (x) {
10381 if (oWins()) {
10382 o.onNext(x);
10383 var timeout = tryCatch(timeoutDurationSelector)(x);
10384 if (timeout === errorObj) { return o.onError(timeout.e); }
10385 setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
10386 }
10387 }, function (e) {
10388 oWins() && o.onError(e);
10389 }, function () {
10390 oWins() && o.onCompleted();
10391 }));
10392 return new BinaryDisposable(subscription, timer);
10393 }, source);
10394 }
10395
10396 function timeout(source, dueTime, other, scheduler) {
10397 if (isScheduler(other)) {
10398 scheduler = other;
10399 other = observableThrow(new TimeoutError());
10400 }
10401 if (other instanceof Error) { other = observableThrow(other); }
10402 isScheduler(scheduler) || (scheduler = defaultScheduler);
10403 Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
10404 return new AnonymousObservable(function (o) {
10405 var id = 0,
10406 original = new SingleAssignmentDisposable(),
10407 subscription = new SerialDisposable(),
10408 switched = false,
10409 timer = new SerialDisposable();
10410
10411 subscription.setDisposable(original);
10412
10413 function createTimer() {
10414 var myId = id;
10415 timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () {
10416 switched = id === myId;
10417 if (switched) {
10418 isPromise(other) && (other = observableFromPromise(other));
10419 subscription.setDisposable(other.subscribe(o));
10420 }
10421 }));
10422 }
10423
10424 createTimer();
10425
10426 original.setDisposable(source.subscribe(function (x) {
10427 if (!switched) {
10428 id++;
10429 o.onNext(x);
10430 createTimer();
10431 }
10432 }, function (e) {
10433 if (!switched) {
10434 id++;
10435 o.onError(e);
10436 }
10437 }, function () {
10438 if (!switched) {
10439 id++;
10440 o.onCompleted();
10441 }
10442 }));
10443 return new BinaryDisposable(subscription, timer);
10444 }, source);
10445 }
10446
10447 observableProto.timeout = function () {
10448 var firstArg = arguments[0];
10449 if (firstArg instanceof Date || typeof firstArg === 'number') {
10450 return timeout(this, firstArg, arguments[1], arguments[2]);
10451 } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
10452 return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]);
10453 } else {
10454 throw new Error('Invalid arguments');
10455 }
10456 };
10457
10458 var GenerateAbsoluteObservable = (function (__super__) {
10459 inherits(GenerateAbsoluteObservable, __super__);
10460 function GenerateAbsoluteObservable(state, cndFn, itrFn, resFn, timeFn, s) {
10461 this._state = state;
10462 this._cndFn = cndFn;
10463 this._itrFn = itrFn;
10464 this._resFn = resFn;
10465 this._timeFn = timeFn;
10466 this._s = s;
10467 this._first = true;
10468 this._hasResult = false;
10469 __super__.call(this);
10470 }
10471
10472 function scheduleRecursive(self, recurse) {
10473 self._hasResult && self._o.onNext(self._state);
10474
10475 if (self._first) {
10476 self._first = false;
10477 } else {
10478 self._state = tryCatch(self._itrFn)(self._state);
10479 if (self._state === errorObj) { return self._o.onError(self._state.e); }
10480 }
10481 self._hasResult = tryCatch(self._cndFn)(self._state);
10482 if (self._hasResult === errorObj) { return self._o.onError(self._hasResult.e); }
10483 if (self._hasResult) {
10484 var result = tryCatch(self._resFn)(self._state);
10485 if (result === errorObj) { return self._o.onError(result.e); }
10486 var time = tryCatch(self._timeFn)(self._state);
10487 if (time === errorObj) { return self._o.onError(time.e); }
10488 recurse(self, time);
10489 } else {
10490 self._o.onCompleted();
10491 }
10492 }
10493
10494 GenerateAbsoluteObservable.prototype.subscribeCore = function (o) {
10495 this._o = o;
10496 return this._s.scheduleRecursiveFuture(this, new Date(this._s.now()), scheduleRecursive);
10497 };
10498
10499 return GenerateAbsoluteObservable;
10500 }(ObservableBase));
10501
10502 /**
10503 * GenerateAbsolutes an observable sequence by iterating a state from an initial state until the condition fails.
10504 *
10505 * @example
10506 * res = source.generateWithAbsoluteTime(0,
10507 * function (x) { return return true; },
10508 * function (x) { return x + 1; },
10509 * function (x) { return x; },
10510 * function (x) { return new Date(); }
10511 * });
10512 *
10513 * @param {Mixed} initialState Initial state.
10514 * @param {Function} condition Condition to terminate generation (upon returning false).
10515 * @param {Function} iterate Iteration step function.
10516 * @param {Function} resultSelector Selector function for results produced in the sequence.
10517 * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
10518 * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
10519 * @returns {Observable} The generated sequence.
10520 */
10521 Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
10522 isScheduler(scheduler) || (scheduler = defaultScheduler);
10523 return new GenerateAbsoluteObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
10524 };
10525
10526 var GenerateRelativeObservable = (function (__super__) {
10527 inherits(GenerateRelativeObservable, __super__);
10528 function GenerateRelativeObservable(state, cndFn, itrFn, resFn, timeFn, s) {
10529 this._state = state;
10530 this._cndFn = cndFn;
10531 this._itrFn = itrFn;
10532 this._resFn = resFn;
10533 this._timeFn = timeFn;
10534 this._s = s;
10535 this._first = true;
10536 this._hasResult = false;
10537 __super__.call(this);
10538 }
10539
10540 function scheduleRecursive(self, recurse) {
10541 self._hasResult && self._o.onNext(self._state);
10542
10543 if (self._first) {
10544 self._first = false;
10545 } else {
10546 self._state = tryCatch(self._itrFn)(self._state);
10547 if (self._state === errorObj) { return self._o.onError(self._state.e); }
10548 }
10549 self._hasResult = tryCatch(self._cndFn)(self._state);
10550 if (self._hasResult === errorObj) { return self._o.onError(self._hasResult.e); }
10551 if (self._hasResult) {
10552 var result = tryCatch(self._resFn)(self._state);
10553 if (result === errorObj) { return self._o.onError(result.e); }
10554 var time = tryCatch(self._timeFn)(self._state);
10555 if (time === errorObj) { return self._o.onError(time.e); }
10556 recurse(self, time);
10557 } else {
10558 self._o.onCompleted();
10559 }
10560 }
10561
10562 GenerateRelativeObservable.prototype.subscribeCore = function (o) {
10563 this._o = o;
10564 return this._s.scheduleRecursiveFuture(this, 0, scheduleRecursive);
10565 };
10566
10567 return GenerateRelativeObservable;
10568 }(ObservableBase));
10569
10570 /**
10571 * Generates an observable sequence by iterating a state from an initial state until the condition fails.
10572 *
10573 * @example
10574 * res = source.generateWithRelativeTime(0,
10575 * function (x) { return return true; },
10576 * function (x) { return x + 1; },
10577 * function (x) { return x; },
10578 * function (x) { return 500; }
10579 * );
10580 *
10581 * @param {Mixed} initialState Initial state.
10582 * @param {Function} condition Condition to terminate generation (upon returning false).
10583 * @param {Function} iterate Iteration step function.
10584 * @param {Function} resultSelector Selector function for results produced in the sequence.
10585 * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
10586 * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
10587 * @returns {Observable} The generated sequence.
10588 */
10589 Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
10590 isScheduler(scheduler) || (scheduler = defaultScheduler);
10591 return new GenerateRelativeObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
10592 };
10593
10594 var DelaySubscription = (function(__super__) {
10595 inherits(DelaySubscription, __super__);
10596 function DelaySubscription(source, dt, s) {
10597 this.source = source;
10598 this._dt = dt;
10599 this._s = s;
10600 __super__.call(this);
10601 }
10602
10603 DelaySubscription.prototype.subscribeCore = function (o) {
10604 var d = new SerialDisposable();
10605
10606 d.setDisposable(this._s.scheduleFuture([this.source, o, d], this._dt, scheduleMethod));
10607
10608 return d;
10609 };
10610
10611 function scheduleMethod(s, state) {
10612 var source = state[0], o = state[1], d = state[2];
10613 d.setDisposable(source.subscribe(o));
10614 }
10615
10616 return DelaySubscription;
10617 }(ObservableBase));
10618
10619 /**
10620 * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
10621 *
10622 * @example
10623 * 1 - res = source.delaySubscription(5000); // 5s
10624 * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
10625 *
10626 * @param {Number} dueTime Relative or absolute time shift of the subscription.
10627 * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
10628 * @returns {Observable} Time-shifted sequence.
10629 */
10630 observableProto.delaySubscription = function (dueTime, scheduler) {
10631 isScheduler(scheduler) || (scheduler = defaultScheduler);
10632 return new DelaySubscription(this, dueTime, scheduler);
10633 };
10634
10635 var SkipLastWithTimeObservable = (function (__super__) {
10636 inherits(SkipLastWithTimeObservable, __super__);
10637 function SkipLastWithTimeObservable(source, d, s) {
10638 this.source = source;
10639 this._d = d;
10640 this._s = s;
10641 __super__.call(this);
10642 }
10643
10644 SkipLastWithTimeObservable.prototype.subscribeCore = function (o) {
10645 return this.source.subscribe(new SkipLastWithTimeObserver(o, this));
10646 };
10647
10648 return SkipLastWithTimeObservable;
10649 }(ObservableBase));
10650
10651 var SkipLastWithTimeObserver = (function (__super__) {
10652 inherits(SkipLastWithTimeObserver, __super__);
10653
10654 function SkipLastWithTimeObserver(o, p) {
10655 this._o = o;
10656 this._s = p._s;
10657 this._d = p._d;
10658 this._q = [];
10659 __super__.call(this);
10660 }
10661
10662 SkipLastWithTimeObserver.prototype.next = function (x) {
10663 var now = this._s.now();
10664 this._q.push({ interval: now, value: x });
10665 while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
10666 this._o.onNext(this._q.shift().value);
10667 }
10668 };
10669 SkipLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
10670 SkipLastWithTimeObserver.prototype.completed = function () {
10671 var now = this._s.now();
10672 while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
10673 this._o.onNext(this._q.shift().value);
10674 }
10675 this._o.onCompleted();
10676 };
10677
10678 return SkipLastWithTimeObserver;
10679 }(AbstractObserver));
10680
10681 /**
10682 * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
10683 * @description
10684 * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
10685 * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
10686 * result sequence. This causes elements to be delayed with duration.
10687 * @param {Number} duration Duration for skipping elements from the end of the sequence.
10688 * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
10689 * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
10690 */
10691 observableProto.skipLastWithTime = function (duration, scheduler) {
10692 isScheduler(scheduler) || (scheduler = defaultScheduler);
10693 return new SkipLastWithTimeObservable(this, duration, scheduler);
10694 };
10695
10696 var TakeLastWithTimeObservable = (function (__super__) {
10697 inherits(TakeLastWithTimeObservable, __super__);
10698 function TakeLastWithTimeObservable(source, d, s) {
10699 this.source = source;
10700 this._d = d;
10701 this._s = s;
10702 __super__.call(this);
10703 }
10704
10705 TakeLastWithTimeObservable.prototype.subscribeCore = function (o) {
10706 return this.source.subscribe(new TakeLastWithTimeObserver(o, this._d, this._s));
10707 };
10708
10709 return TakeLastWithTimeObservable;
10710 }(ObservableBase));
10711
10712 var TakeLastWithTimeObserver = (function (__super__) {
10713 inherits(TakeLastWithTimeObserver, __super__);
10714
10715 function TakeLastWithTimeObserver(o, d, s) {
10716 this._o = o;
10717 this._d = d;
10718 this._s = s;
10719 this._q = [];
10720 __super__.call(this);
10721 }
10722
10723 TakeLastWithTimeObserver.prototype.next = function (x) {
10724 var now = this._s.now();
10725 this._q.push({ interval: now, value: x });
10726 while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
10727 this._q.shift();
10728 }
10729 };
10730 TakeLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
10731 TakeLastWithTimeObserver.prototype.completed = function () {
10732 var now = this._s.now();
10733 while (this._q.length > 0) {
10734 var next = this._q.shift();
10735 if (now - next.interval <= this._d) { this._o.onNext(next.value); }
10736 }
10737 this._o.onCompleted();
10738 };
10739
10740 return TakeLastWithTimeObserver;
10741 }(AbstractObserver));
10742
10743 /**
10744 * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
10745 * @description
10746 * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
10747 * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
10748 * result sequence. This causes elements to be delayed with duration.
10749 * @param {Number} duration Duration for taking elements from the end of the sequence.
10750 * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
10751 * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
10752 */
10753 observableProto.takeLastWithTime = function (duration, scheduler) {
10754 isScheduler(scheduler) || (scheduler = defaultScheduler);
10755 return new TakeLastWithTimeObservable(this, duration, scheduler);
10756 };
10757
10758 /**
10759 * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
10760 * @description
10761 * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
10762 * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
10763 * result sequence. This causes elements to be delayed with duration.
10764 * @param {Number} duration Duration for taking elements from the end of the sequence.
10765 * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
10766 * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
10767 */
10768 observableProto.takeLastBufferWithTime = function (duration, scheduler) {
10769 var source = this;
10770 isScheduler(scheduler) || (scheduler = defaultScheduler);
10771 return new AnonymousObservable(function (o) {
10772 var q = [];
10773 return source.subscribe(function (x) {
10774 var now = scheduler.now();
10775 q.push({ interval: now, value: x });
10776 while (q.length > 0 && now - q[0].interval >= duration) {
10777 q.shift();
10778 }
10779 }, function (e) { o.onError(e); }, function () {
10780 var now = scheduler.now(), res = [];
10781 while (q.length > 0) {
10782 var next = q.shift();
10783 now - next.interval <= duration && res.push(next.value);
10784 }
10785 o.onNext(res);
10786 o.onCompleted();
10787 });
10788 }, source);
10789 };
10790
10791 var TakeWithTimeObservable = (function (__super__) {
10792 inherits(TakeWithTimeObservable, __super__);
10793 function TakeWithTimeObservable(source, d, s) {
10794 this.source = source;
10795 this._d = d;
10796 this._s = s;
10797 __super__.call(this);
10798 }
10799
10800 function scheduleMethod(s, o) {
10801 o.onCompleted();
10802 }
10803
10804 TakeWithTimeObservable.prototype.subscribeCore = function (o) {
10805 return new BinaryDisposable(
10806 this._s.scheduleFuture(o, this._d, scheduleMethod),
10807 this.source.subscribe(o)
10808 );
10809 };
10810
10811 return TakeWithTimeObservable;
10812 }(ObservableBase));
10813
10814 /**
10815 * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
10816 *
10817 * @example
10818 * 1 - res = source.takeWithTime(5000, [optional scheduler]);
10819 * @description
10820 * This operator accumulates a queue with a length enough to store elements received during the initial duration window.
10821 * As more elements are received, elements older than the specified duration are taken from the queue and produced on the
10822 * result sequence. This causes elements to be delayed with duration.
10823 * @param {Number} duration Duration for taking elements from the start of the sequence.
10824 * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
10825 * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
10826 */
10827 observableProto.takeWithTime = function (duration, scheduler) {
10828 isScheduler(scheduler) || (scheduler = defaultScheduler);
10829 return new TakeWithTimeObservable(this, duration, scheduler);
10830 };
10831
10832 var SkipWithTimeObservable = (function (__super__) {
10833 inherits(SkipWithTimeObservable, __super__);
10834 function SkipWithTimeObservable(source, d, s) {
10835 this.source = source;
10836 this._d = d;
10837 this._s = s;
10838 this._open = false;
10839 __super__.call(this);
10840 }
10841
10842 function scheduleMethod(s, self) {
10843 self._open = true;
10844 }
10845
10846 SkipWithTimeObservable.prototype.subscribeCore = function (o) {
10847 return new BinaryDisposable(
10848 this._s.scheduleFuture(this, this._d, scheduleMethod),
10849 this.source.subscribe(new SkipWithTimeObserver(o, this))
10850 );
10851 };
10852
10853 return SkipWithTimeObservable;
10854 }(ObservableBase));
10855
10856 var SkipWithTimeObserver = (function (__super__) {
10857 inherits(SkipWithTimeObserver, __super__);
10858
10859 function SkipWithTimeObserver(o, p) {
10860 this._o = o;
10861 this._p = p;
10862 __super__.call(this);
10863 }
10864
10865 SkipWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
10866 SkipWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
10867 SkipWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
10868
10869 return SkipWithTimeObserver;
10870 }(AbstractObserver));
10871
10872 /**
10873 * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
10874 * @description
10875 * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
10876 * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
10877 * may not execute immediately, despite the zero due time.
10878 *
10879 * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
10880 * @param {Number} duration Duration for skipping elements from the start of the sequence.
10881 * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
10882 * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
10883 */
10884 observableProto.skipWithTime = function (duration, scheduler) {
10885 isScheduler(scheduler) || (scheduler = defaultScheduler);
10886 return new SkipWithTimeObservable(this, duration, scheduler);
10887 };
10888
10889 var SkipUntilWithTimeObservable = (function (__super__) {
10890 inherits(SkipUntilWithTimeObservable, __super__);
10891 function SkipUntilWithTimeObservable(source, startTime, scheduler) {
10892 this.source = source;
10893 this._st = startTime;
10894 this._s = scheduler;
10895 __super__.call(this);
10896 }
10897
10898 function scheduleMethod(s, state) {
10899 state._open = true;
10900 }
10901
10902 SkipUntilWithTimeObservable.prototype.subscribeCore = function (o) {
10903 this._open = false;
10904 return new BinaryDisposable(
10905 this._s.scheduleFuture(this, this._st, scheduleMethod),
10906 this.source.subscribe(new SkipUntilWithTimeObserver(o, this))
10907 );
10908 };
10909
10910 return SkipUntilWithTimeObservable;
10911 }(ObservableBase));
10912
10913 var SkipUntilWithTimeObserver = (function (__super__) {
10914 inherits(SkipUntilWithTimeObserver, __super__);
10915
10916 function SkipUntilWithTimeObserver(o, p) {
10917 this._o = o;
10918 this._p = p;
10919 __super__.call(this);
10920 }
10921
10922 SkipUntilWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
10923 SkipUntilWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
10924 SkipUntilWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
10925
10926 return SkipUntilWithTimeObserver;
10927 }(AbstractObserver));
10928
10929
10930 /**
10931 * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
10932 * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
10933 *
10934 * @examples
10935 * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
10936 * 2 - res = source.skipUntilWithTime(5000, [scheduler]);
10937 * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
10938 * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
10939 * @returns {Observable} An observable sequence with the elements skipped until the specified start time.
10940 */
10941 observableProto.skipUntilWithTime = function (startTime, scheduler) {
10942 isScheduler(scheduler) || (scheduler = defaultScheduler);
10943 return new SkipUntilWithTimeObservable(this, startTime, scheduler);
10944 };
10945
10946 /**
10947 * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
10948 * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
10949 * @param {Scheduler} [scheduler] Scheduler to run the timer on.
10950 * @returns {Observable} An observable sequence with the elements taken until the specified end time.
10951 */
10952 observableProto.takeUntilWithTime = function (endTime, scheduler) {
10953 isScheduler(scheduler) || (scheduler = defaultScheduler);
10954 var source = this;
10955 return new AnonymousObservable(function (o) {
10956 return new BinaryDisposable(
10957 scheduler.scheduleFuture(o, endTime, function (_, o) { o.onCompleted(); }),
10958 source.subscribe(o));
10959 }, source);
10960 };
10961
10962 /**
10963 * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
10964 * @param {Number} windowDuration time to wait before emitting another item after emitting the last item
10965 * @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.
10966 * @returns {Observable} An Observable that performs the throttle operation.
10967 */
10968 observableProto.throttle = function (windowDuration, scheduler) {
10969 isScheduler(scheduler) || (scheduler = defaultScheduler);
10970 var duration = +windowDuration || 0;
10971 if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
10972 var source = this;
10973 return new AnonymousObservable(function (o) {
10974 var lastOnNext = 0;
10975 return source.subscribe(
10976 function (x) {
10977 var now = scheduler.now();
10978 if (lastOnNext === 0 || now - lastOnNext >= duration) {
10979 lastOnNext = now;
10980 o.onNext(x);
10981 }
10982 },function (e) { o.onError(e); }, function () { o.onCompleted(); }
10983 );
10984 }, source);
10985 };
10986
10987 var SwitchFirstObservable = (function (__super__) {
10988 inherits(SwitchFirstObservable, __super__);
10989 function SwitchFirstObservable(source) {
10990 this.source = source;
10991 __super__.call(this);
10992 }
10993
10994 SwitchFirstObservable.prototype.subscribeCore = function (o) {
10995 var m = new SingleAssignmentDisposable(),
10996 g = new CompositeDisposable(),
10997 state = {
10998 hasCurrent: false,
10999 isStopped: false,
11000 o: o,
11001 g: g
11002 };
11003
11004 g.add(m);
11005 m.setDisposable(this.source.subscribe(new SwitchFirstObserver(state)));
11006 return g;
11007 };
11008
11009 return SwitchFirstObservable;
11010 }(ObservableBase));
11011
11012 var SwitchFirstObserver = (function(__super__) {
11013 inherits(SwitchFirstObserver, __super__);
11014 function SwitchFirstObserver(state) {
11015 this._s = state;
11016 __super__.call(this);
11017 }
11018
11019 SwitchFirstObserver.prototype.next = function (x) {
11020 if (!this._s.hasCurrent) {
11021 this._s.hasCurrent = true;
11022 isPromise(x) && (x = observableFromPromise(x));
11023 var inner = new SingleAssignmentDisposable();
11024 this._s.g.add(inner);
11025 inner.setDisposable(x.subscribe(new InnerObserver(this._s, inner)));
11026 }
11027 };
11028
11029 SwitchFirstObserver.prototype.error = function (e) {
11030 this._s.o.onError(e);
11031 };
11032
11033 SwitchFirstObserver.prototype.completed = function () {
11034 this._s.isStopped = true;
11035 !this._s.hasCurrent && this._s.g.length === 1 && this._s.o.onCompleted();
11036 };
11037
11038 inherits(InnerObserver, __super__);
11039 function InnerObserver(state, inner) {
11040 this._s = state;
11041 this._i = inner;
11042 __super__.call(this);
11043 }
11044
11045 InnerObserver.prototype.next = function (x) { this._s.o.onNext(x); };
11046 InnerObserver.prototype.error = function (e) { this._s.o.onError(e); };
11047 InnerObserver.prototype.completed = function () {
11048 this._s.g.remove(this._i);
11049 this._s.hasCurrent = false;
11050 this._s.isStopped && this._s.g.length === 1 && this._s.o.onCompleted();
11051 };
11052
11053 return SwitchFirstObserver;
11054 }(AbstractObserver));
11055
11056 /**
11057 * Performs a exclusive waiting for the first to finish before subscribing to another observable.
11058 * Observables that come in between subscriptions will be dropped on the floor.
11059 * @returns {Observable} A exclusive observable with only the results that happen when subscribed.
11060 */
11061 observableProto.switchFirst = function () {
11062 return new SwitchFirstObservable(this);
11063 };
11064
11065observableProto.flatMapFirst = observableProto.selectManyFirst = function(selector, resultSelector, thisArg) {
11066 return new FlatMapObservable(this, selector, resultSelector, thisArg).switchFirst();
11067};
11068
11069Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit, selector, resultSelector, thisArg) {
11070 return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit);
11071};
11072 var TransduceObserver = (function (__super__) {
11073 inherits(TransduceObserver, __super__);
11074 function TransduceObserver(o, xform) {
11075 this._o = o;
11076 this._xform = xform;
11077 __super__.call(this);
11078 }
11079
11080 TransduceObserver.prototype.next = function (x) {
11081 var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x);
11082 if (res === errorObj) { this._o.onError(res.e); }
11083 };
11084
11085 TransduceObserver.prototype.error = function (e) { this._o.onError(e); };
11086
11087 TransduceObserver.prototype.completed = function () {
11088 this._xform['@@transducer/result'](this._o);
11089 };
11090
11091 return TransduceObserver;
11092 }(AbstractObserver));
11093
11094 function transformForObserver(o) {
11095 return {
11096 '@@transducer/init': function() {
11097 return o;
11098 },
11099 '@@transducer/step': function(obs, input) {
11100 return obs.onNext(input);
11101 },
11102 '@@transducer/result': function(obs) {
11103 return obs.onCompleted();
11104 }
11105 };
11106 }
11107
11108 /**
11109 * Executes a transducer to transform the observable sequence
11110 * @param {Transducer} transducer A transducer to execute
11111 * @returns {Observable} An Observable sequence containing the results from the transducer.
11112 */
11113 observableProto.transduce = function(transducer) {
11114 var source = this;
11115 return new AnonymousObservable(function(o) {
11116 var xform = transducer(transformForObserver(o));
11117 return source.subscribe(new TransduceObserver(o, xform));
11118 }, source);
11119 };
11120
11121 /** Provides a set of extension methods for virtual time scheduling. */
11122 var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) {
11123 inherits(VirtualTimeScheduler, __super__);
11124
11125 /**
11126 * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
11127 *
11128 * @constructor
11129 * @param {Number} initialClock Initial value for the clock.
11130 * @param {Function} comparer Comparer to determine causality of events based on absolute time.
11131 */
11132 function VirtualTimeScheduler(initialClock, comparer) {
11133 this.clock = initialClock;
11134 this.comparer = comparer;
11135 this.isEnabled = false;
11136 this.queue = new PriorityQueue(1024);
11137 __super__.call(this);
11138 }
11139
11140 var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
11141
11142 VirtualTimeSchedulerPrototype.now = function () {
11143 return this.toAbsoluteTime(this.clock);
11144 };
11145
11146 VirtualTimeSchedulerPrototype.schedule = function (state, action) {
11147 return this.scheduleAbsolute(state, this.clock, action);
11148 };
11149
11150 VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) {
11151 var dt = dueTime instanceof Date ?
11152 this.toRelativeTime(dueTime - this.now()) :
11153 this.toRelativeTime(dueTime);
11154
11155 return this.scheduleRelative(state, dt, action);
11156 };
11157
11158 /**
11159 * Adds a relative time value to an absolute time value.
11160 * @param {Number} absolute Absolute virtual time value.
11161 * @param {Number} relative Relative virtual time value to add.
11162 * @return {Number} Resulting absolute virtual time sum value.
11163 */
11164 VirtualTimeSchedulerPrototype.add = notImplemented;
11165
11166 /**
11167 * Converts an absolute time to a number
11168 * @param {Any} The absolute time.
11169 * @returns {Number} The absolute time in ms
11170 */
11171 VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented;
11172
11173 /**
11174 * Converts the TimeSpan value to a relative virtual time value.
11175 * @param {Number} timeSpan TimeSpan value to convert.
11176 * @return {Number} Corresponding relative virtual time value.
11177 */
11178 VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented;
11179
11180 /**
11181 * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
11182 * @param {Mixed} state Initial state passed to the action upon the first iteration.
11183 * @param {Number} period Period for running the work periodically.
11184 * @param {Function} action Action to be executed, potentially updating the state.
11185 * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
11186 */
11187 VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) {
11188 var s = new SchedulePeriodicRecursive(this, state, period, action);
11189 return s.start();
11190 };
11191
11192 /**
11193 * Schedules an action to be executed after dueTime.
11194 * @param {Mixed} state State passed to the action to be executed.
11195 * @param {Number} dueTime Relative time after which to execute the action.
11196 * @param {Function} action Action to be executed.
11197 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
11198 */
11199 VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) {
11200 var runAt = this.add(this.clock, dueTime);
11201 return this.scheduleAbsolute(state, runAt, action);
11202 };
11203
11204 /**
11205 * Starts the virtual time scheduler.
11206 */
11207 VirtualTimeSchedulerPrototype.start = function () {
11208 if (!this.isEnabled) {
11209 this.isEnabled = true;
11210 do {
11211 var next = this.getNext();
11212 if (next !== null) {
11213 this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
11214 next.invoke();
11215 } else {
11216 this.isEnabled = false;
11217 }
11218 } while (this.isEnabled);
11219 }
11220 };
11221
11222 /**
11223 * Stops the virtual time scheduler.
11224 */
11225 VirtualTimeSchedulerPrototype.stop = function () {
11226 this.isEnabled = false;
11227 };
11228
11229 /**
11230 * Advances the scheduler's clock to the specified time, running all work till that point.
11231 * @param {Number} time Absolute time to advance the scheduler's clock to.
11232 */
11233 VirtualTimeSchedulerPrototype.advanceTo = function (time) {
11234 var dueToClock = this.comparer(this.clock, time);
11235 if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
11236 if (dueToClock === 0) { return; }
11237 if (!this.isEnabled) {
11238 this.isEnabled = true;
11239 do {
11240 var next = this.getNext();
11241 if (next !== null && this.comparer(next.dueTime, time) <= 0) {
11242 this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
11243 next.invoke();
11244 } else {
11245 this.isEnabled = false;
11246 }
11247 } while (this.isEnabled);
11248 this.clock = time;
11249 }
11250 };
11251
11252 /**
11253 * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
11254 * @param {Number} time Relative time to advance the scheduler's clock by.
11255 */
11256 VirtualTimeSchedulerPrototype.advanceBy = function (time) {
11257 var dt = this.add(this.clock, time),
11258 dueToClock = this.comparer(this.clock, dt);
11259 if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
11260 if (dueToClock === 0) { return; }
11261
11262 this.advanceTo(dt);
11263 };
11264
11265 /**
11266 * Advances the scheduler's clock by the specified relative time.
11267 * @param {Number} time Relative time to advance the scheduler's clock by.
11268 */
11269 VirtualTimeSchedulerPrototype.sleep = function (time) {
11270 var dt = this.add(this.clock, time);
11271 if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
11272
11273 this.clock = dt;
11274 };
11275
11276 /**
11277 * Gets the next scheduled item to be executed.
11278 * @returns {ScheduledItem} The next scheduled item.
11279 */
11280 VirtualTimeSchedulerPrototype.getNext = function () {
11281 while (this.queue.length > 0) {
11282 var next = this.queue.peek();
11283 if (next.isCancelled()) {
11284 this.queue.dequeue();
11285 } else {
11286 return next;
11287 }
11288 }
11289 return null;
11290 };
11291
11292 /**
11293 * Schedules an action to be executed at dueTime.
11294 * @param {Mixed} state State passed to the action to be executed.
11295 * @param {Number} dueTime Absolute time at which to execute the action.
11296 * @param {Function} action Action to be executed.
11297 * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
11298 */
11299 VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) {
11300 var self = this;
11301
11302 function run(scheduler, state1) {
11303 self.queue.remove(si);
11304 return action(scheduler, state1);
11305 }
11306
11307 var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
11308 this.queue.enqueue(si);
11309
11310 return si.disposable;
11311 };
11312
11313 return VirtualTimeScheduler;
11314 }(Scheduler));
11315
11316 /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
11317 Rx.HistoricalScheduler = (function (__super__) {
11318 inherits(HistoricalScheduler, __super__);
11319
11320 /**
11321 * Creates a new historical scheduler with the specified initial clock value.
11322 * @constructor
11323 * @param {Number} initialClock Initial value for the clock.
11324 * @param {Function} comparer Comparer to determine causality of events based on absolute time.
11325 */
11326 function HistoricalScheduler(initialClock, comparer) {
11327 var clock = initialClock == null ? 0 : initialClock;
11328 var cmp = comparer || defaultSubComparer;
11329 __super__.call(this, clock, cmp);
11330 }
11331
11332 var HistoricalSchedulerProto = HistoricalScheduler.prototype;
11333
11334 /**
11335 * Adds a relative time value to an absolute time value.
11336 * @param {Number} absolute Absolute virtual time value.
11337 * @param {Number} relative Relative virtual time value to add.
11338 * @return {Number} Resulting absolute virtual time sum value.
11339 */
11340 HistoricalSchedulerProto.add = function (absolute, relative) {
11341 return absolute + relative;
11342 };
11343
11344 HistoricalSchedulerProto.toAbsoluteTime = function (absolute) {
11345 return new Date(absolute).getTime();
11346 };
11347
11348 /**
11349 * Converts the TimeSpan value to a relative virtual time value.
11350 * @memberOf HistoricalScheduler
11351 * @param {Number} timeSpan TimeSpan value to convert.
11352 * @return {Number} Corresponding relative virtual time value.
11353 */
11354 HistoricalSchedulerProto.toRelativeTime = function (timeSpan) {
11355 return timeSpan;
11356 };
11357
11358 return HistoricalScheduler;
11359 }(Rx.VirtualTimeScheduler));
11360
11361function OnNextPredicate(predicate) {
11362 this.predicate = predicate;
11363}
11364
11365OnNextPredicate.prototype.equals = function (other) {
11366 if (other === this) { return true; }
11367 if (other == null) { return false; }
11368 if (other.kind !== 'N') { return false; }
11369 return this.predicate(other.value);
11370};
11371
11372function OnErrorPredicate(predicate) {
11373 this.predicate = predicate;
11374}
11375
11376OnErrorPredicate.prototype.equals = function (other) {
11377 if (other === this) { return true; }
11378 if (other == null) { return false; }
11379 if (other.kind !== 'E') { return false; }
11380 return this.predicate(other.error);
11381};
11382
11383var ReactiveTest = Rx.ReactiveTest = {
11384 /** Default virtual time used for creation of observable sequences in unit tests. */
11385 created: 100,
11386 /** Default virtual time used to subscribe to observable sequences in unit tests. */
11387 subscribed: 200,
11388 /** Default virtual time used to dispose subscriptions in unit tests. */
11389 disposed: 1000,
11390
11391 /**
11392 * Factory method for an OnNext notification record at a given time with a given value or a predicate function.
11393 *
11394 * 1 - ReactiveTest.onNext(200, 42);
11395 * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; });
11396 *
11397 * @param ticks Recorded virtual time the OnNext notification occurs.
11398 * @param value Recorded value stored in the OnNext notification or a predicate.
11399 * @return Recorded OnNext notification.
11400 */
11401 onNext: function (ticks, value) {
11402 return typeof value === 'function' ?
11403 new Recorded(ticks, new OnNextPredicate(value)) :
11404 new Recorded(ticks, Notification.createOnNext(value));
11405 },
11406 /**
11407 * Factory method for an OnError notification record at a given time with a given error.
11408 *
11409 * 1 - ReactiveTest.onNext(200, new Error('error'));
11410 * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; });
11411 *
11412 * @param ticks Recorded virtual time the OnError notification occurs.
11413 * @param exception Recorded exception stored in the OnError notification.
11414 * @return Recorded OnError notification.
11415 */
11416 onError: function (ticks, error) {
11417 return typeof error === 'function' ?
11418 new Recorded(ticks, new OnErrorPredicate(error)) :
11419 new Recorded(ticks, Notification.createOnError(error));
11420 },
11421 /**
11422 * Factory method for an OnCompleted notification record at a given time.
11423 *
11424 * @param ticks Recorded virtual time the OnCompleted notification occurs.
11425 * @return Recorded OnCompleted notification.
11426 */
11427 onCompleted: function (ticks) {
11428 return new Recorded(ticks, Notification.createOnCompleted());
11429 },
11430 /**
11431 * Factory method for a subscription record based on a given subscription and disposal time.
11432 *
11433 * @param start Virtual time indicating when the subscription was created.
11434 * @param end Virtual time indicating when the subscription was disposed.
11435 * @return Subscription object.
11436 */
11437 subscribe: function (start, end) {
11438 return new Subscription(start, end);
11439 }
11440};
11441
11442 /**
11443 * Creates a new object recording the production of the specified value at the given virtual time.
11444 *
11445 * @constructor
11446 * @param {Number} time Virtual time the value was produced on.
11447 * @param {Mixed} value Value that was produced.
11448 * @param {Function} comparer An optional comparer.
11449 */
11450 var Recorded = Rx.Recorded = function (time, value, comparer) {
11451 this.time = time;
11452 this.value = value;
11453 this.comparer = comparer || defaultComparer;
11454 };
11455
11456 /**
11457 * Checks whether the given recorded object is equal to the current instance.
11458 *
11459 * @param {Recorded} other Recorded object to check for equality.
11460 * @returns {Boolean} true if both objects are equal; false otherwise.
11461 */
11462 Recorded.prototype.equals = function (other) {
11463 return this.time === other.time && this.comparer(this.value, other.value);
11464 };
11465
11466 /**
11467 * Returns a string representation of the current Recorded value.
11468 *
11469 * @returns {String} String representation of the current Recorded value.
11470 */
11471 Recorded.prototype.toString = function () {
11472 return this.value.toString() + '@' + this.time;
11473 };
11474
11475 /**
11476 * Creates a new subscription object with the given virtual subscription and unsubscription time.
11477 *
11478 * @constructor
11479 * @param {Number} subscribe Virtual time at which the subscription occurred.
11480 * @param {Number} unsubscribe Virtual time at which the unsubscription occurred.
11481 */
11482 var Subscription = Rx.Subscription = function (start, end) {
11483 this.subscribe = start;
11484 this.unsubscribe = end || Number.MAX_VALUE;
11485 };
11486
11487 /**
11488 * Checks whether the given subscription is equal to the current instance.
11489 * @param other Subscription object to check for equality.
11490 * @returns {Boolean} true if both objects are equal; false otherwise.
11491 */
11492 Subscription.prototype.equals = function (other) {
11493 return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe;
11494 };
11495
11496 /**
11497 * Returns a string representation of the current Subscription value.
11498 * @returns {String} String representation of the current Subscription value.
11499 */
11500 Subscription.prototype.toString = function () {
11501 return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')';
11502 };
11503
11504 var MockDisposable = Rx.MockDisposable = function (scheduler) {
11505 this.scheduler = scheduler;
11506 this.disposes = [];
11507 this.disposes.push(this.scheduler.clock);
11508 };
11509
11510 MockDisposable.prototype.dispose = function () {
11511 this.disposes.push(this.scheduler.clock);
11512 };
11513
11514 var MockObserver = (function (__super__) {
11515 inherits(MockObserver, __super__);
11516
11517 function MockObserver(scheduler) {
11518 __super__.call(this);
11519 this.scheduler = scheduler;
11520 this.messages = [];
11521 }
11522
11523 var MockObserverPrototype = MockObserver.prototype;
11524
11525 MockObserverPrototype.onNext = function (value) {
11526 this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value)));
11527 };
11528
11529 MockObserverPrototype.onError = function (e) {
11530 this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(e)));
11531 };
11532
11533 MockObserverPrototype.onCompleted = function () {
11534 this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted()));
11535 };
11536
11537 return MockObserver;
11538 })(Observer);
11539
11540 function MockPromise(scheduler, messages) {
11541 var self = this;
11542 this.scheduler = scheduler;
11543 this.messages = messages;
11544 this.subscriptions = [];
11545 this.observers = [];
11546 for (var i = 0, len = this.messages.length; i < len; i++) {
11547 var message = this.messages[i],
11548 notification = message.value;
11549 (function (innerNotification) {
11550 scheduler.scheduleAbsolute(null, message.time, function () {
11551 var obs = self.observers.slice(0);
11552
11553 for (var j = 0, jLen = obs.length; j < jLen; j++) {
11554 innerNotification.accept(obs[j]);
11555 }
11556 return disposableEmpty;
11557 });
11558 })(notification);
11559 }
11560 }
11561
11562 MockPromise.prototype.then = function (onResolved, onRejected) {
11563 var self = this;
11564
11565 this.subscriptions.push(new Subscription(this.scheduler.clock));
11566 var index = this.subscriptions.length - 1;
11567
11568 var newPromise;
11569
11570 var observer = Rx.Observer.create(
11571 function (x) {
11572 var retValue = onResolved(x);
11573 if (retValue && typeof retValue.then === 'function') {
11574 newPromise = retValue;
11575 } else {
11576 var ticks = self.scheduler.clock;
11577 newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]);
11578 }
11579 var idx = self.observers.indexOf(observer);
11580 self.observers.splice(idx, 1);
11581 self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
11582 },
11583 function (err) {
11584 onRejected(err);
11585 var idx = self.observers.indexOf(observer);
11586 self.observers.splice(idx, 1);
11587 self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
11588 }
11589 );
11590 this.observers.push(observer);
11591
11592 return newPromise || new MockPromise(this.scheduler, this.messages);
11593 };
11594
11595 var HotObservable = (function (__super__) {
11596 inherits(HotObservable, __super__);
11597
11598 function HotObservable(scheduler, messages) {
11599 __super__.call(this);
11600 var message, notification, observable = this;
11601 this.scheduler = scheduler;
11602 this.messages = messages;
11603 this.subscriptions = [];
11604 this.observers = [];
11605 for (var i = 0, len = this.messages.length; i < len; i++) {
11606 message = this.messages[i];
11607 notification = message.value;
11608 (function (innerNotification) {
11609 scheduler.scheduleAbsolute(null, message.time, function () {
11610 var obs = observable.observers.slice(0);
11611
11612 for (var j = 0, jLen = obs.length; j < jLen; j++) {
11613 innerNotification.accept(obs[j]);
11614 }
11615 return disposableEmpty;
11616 });
11617 })(notification);
11618 }
11619 }
11620
11621 HotObservable.prototype._subscribe = function (o) {
11622 var observable = this;
11623 this.observers.push(o);
11624 this.subscriptions.push(new Subscription(this.scheduler.clock));
11625 var index = this.subscriptions.length - 1;
11626 return disposableCreate(function () {
11627 var idx = observable.observers.indexOf(o);
11628 observable.observers.splice(idx, 1);
11629 observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
11630 });
11631 };
11632
11633 return HotObservable;
11634 })(Observable);
11635
11636 var ColdObservable = (function (__super__) {
11637 inherits(ColdObservable, __super__);
11638
11639 function ColdObservable(scheduler, messages) {
11640 __super__.call(this);
11641 this.scheduler = scheduler;
11642 this.messages = messages;
11643 this.subscriptions = [];
11644 }
11645
11646 ColdObservable.prototype._subscribe = function (o) {
11647 var message, notification, observable = this;
11648 this.subscriptions.push(new Subscription(this.scheduler.clock));
11649 var index = this.subscriptions.length - 1;
11650 var d = new CompositeDisposable();
11651 for (var i = 0, len = this.messages.length; i < len; i++) {
11652 message = this.messages[i];
11653 notification = message.value;
11654 (function (innerNotification) {
11655 d.add(observable.scheduler.scheduleRelative(null, message.time, function () {
11656 innerNotification.accept(o);
11657 return disposableEmpty;
11658 }));
11659 })(notification);
11660 }
11661 return disposableCreate(function () {
11662 observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
11663 d.dispose();
11664 });
11665 };
11666
11667 return ColdObservable;
11668 })(Observable);
11669
11670 /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */
11671 Rx.TestScheduler = (function (__super__) {
11672 inherits(TestScheduler, __super__);
11673
11674 function baseComparer(x, y) {
11675 return x > y ? 1 : (x < y ? -1 : 0);
11676 }
11677
11678 function TestScheduler() {
11679 __super__.call(this, 0, baseComparer);
11680 }
11681
11682 /**
11683 * Schedules an action to be executed at the specified virtual time.
11684 *
11685 * @param state State passed to the action to be executed.
11686 * @param dueTime Absolute virtual time at which to execute the action.
11687 * @param action Action to be executed.
11688 * @return Disposable object used to cancel the scheduled action (best effort).
11689 */
11690 TestScheduler.prototype.scheduleAbsolute = function (state, dueTime, action) {
11691 dueTime <= this.clock && (dueTime = this.clock + 1);
11692 return __super__.prototype.scheduleAbsolute.call(this, state, dueTime, action);
11693 };
11694 /**
11695 * Adds a relative virtual time to an absolute virtual time value.
11696 *
11697 * @param absolute Absolute virtual time value.
11698 * @param relative Relative virtual time value to add.
11699 * @return Resulting absolute virtual time sum value.
11700 */
11701 TestScheduler.prototype.add = function (absolute, relative) {
11702 return absolute + relative;
11703 };
11704 /**
11705 * Converts the absolute virtual time value to a DateTimeOffset value.
11706 *
11707 * @param absolute Absolute virtual time value to convert.
11708 * @return Corresponding DateTimeOffset value.
11709 */
11710 TestScheduler.prototype.toAbsoluteTime = function (absolute) {
11711 return new Date(absolute).getTime();
11712 };
11713 /**
11714 * Converts the TimeSpan value to a relative virtual time value.
11715 *
11716 * @param timeSpan TimeSpan value to convert.
11717 * @return Corresponding relative virtual time value.
11718 */
11719 TestScheduler.prototype.toRelativeTime = function (timeSpan) {
11720 return timeSpan;
11721 };
11722 /**
11723 * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription.
11724 *
11725 * @param create Factory method to create an observable sequence.
11726 * @param created Virtual time at which to invoke the factory to create an observable sequence.
11727 * @param subscribed Virtual time at which to subscribe to the created observable sequence.
11728 * @param disposed Virtual time at which to dispose the subscription.
11729 * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
11730 */
11731 TestScheduler.prototype.startScheduler = function (createFn, settings) {
11732 settings || (settings = {});
11733 settings.created == null && (settings.created = ReactiveTest.created);
11734 settings.subscribed == null && (settings.subscribed = ReactiveTest.subscribed);
11735 settings.disposed == null && (settings.disposed = ReactiveTest.disposed);
11736
11737 var observer = this.createObserver(), source, subscription;
11738
11739 this.scheduleAbsolute(null, settings.created, function () {
11740 source = createFn();
11741 return disposableEmpty;
11742 });
11743
11744 this.scheduleAbsolute(null, settings.subscribed, function () {
11745 subscription = source.subscribe(observer);
11746 return disposableEmpty;
11747 });
11748
11749 this.scheduleAbsolute(null, settings.disposed, function () {
11750 subscription.dispose();
11751 return disposableEmpty;
11752 });
11753
11754 this.start();
11755
11756 return observer;
11757 };
11758
11759 /**
11760 * Creates a hot observable using the specified timestamped notification messages either as an array or arguments.
11761 * @param messages Notifications to surface through the created sequence at their specified absolute virtual times.
11762 * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications.
11763 */
11764 TestScheduler.prototype.createHotObservable = function () {
11765 var len = arguments.length, args;
11766 if (Array.isArray(arguments[0])) {
11767 args = arguments[0];
11768 } else {
11769 args = new Array(len);
11770 for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
11771 }
11772 return new HotObservable(this, args);
11773 };
11774
11775 /**
11776 * Creates a cold observable using the specified timestamped notification messages either as an array or arguments.
11777 * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time.
11778 * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications.
11779 */
11780 TestScheduler.prototype.createColdObservable = function () {
11781 var len = arguments.length, args;
11782 if (Array.isArray(arguments[0])) {
11783 args = arguments[0];
11784 } else {
11785 args = new Array(len);
11786 for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
11787 }
11788 return new ColdObservable(this, args);
11789 };
11790
11791 /**
11792 * Creates a resolved promise with the given value and ticks
11793 * @param {Number} ticks The absolute time of the resolution.
11794 * @param {Any} value The value to yield at the given tick.
11795 * @returns {MockPromise} A mock Promise which fulfills with the given value.
11796 */
11797 TestScheduler.prototype.createResolvedPromise = function (ticks, value) {
11798 return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]);
11799 };
11800
11801 /**
11802 * Creates a rejected promise with the given reason and ticks
11803 * @param {Number} ticks The absolute time of the resolution.
11804 * @param {Any} reason The reason for rejection to yield at the given tick.
11805 * @returns {MockPromise} A mock Promise which rejects with the given reason.
11806 */
11807 TestScheduler.prototype.createRejectedPromise = function (ticks, reason) {
11808 return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]);
11809 };
11810
11811 /**
11812 * Creates an observer that records received notification messages and timestamps those.
11813 * @return Observer that can be used to assert the timing of received notifications.
11814 */
11815 TestScheduler.prototype.createObserver = function () {
11816 return new MockObserver(this);
11817 };
11818
11819 return TestScheduler;
11820 })(VirtualTimeScheduler);
11821
11822 var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
11823 inherits(AnonymousObservable, __super__);
11824
11825 // Fix subscriber to check for undefined or function returned to decorate as Disposable
11826 function fixSubscriber(subscriber) {
11827 return subscriber && isFunction(subscriber.dispose) ? subscriber :
11828 isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
11829 }
11830
11831 function setDisposable(s, state) {
11832 var ado = state[0], self = state[1];
11833 var sub = tryCatch(self.__subscribe).call(self, ado);
11834 if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
11835 ado.setDisposable(fixSubscriber(sub));
11836 }
11837
11838 function AnonymousObservable(subscribe, parent) {
11839 this.source = parent;
11840 this.__subscribe = subscribe;
11841 __super__.call(this);
11842 }
11843
11844 AnonymousObservable.prototype._subscribe = function (o) {
11845 var ado = new AutoDetachObserver(o), state = [ado, this];
11846
11847 if (currentThreadScheduler.scheduleRequired()) {
11848 currentThreadScheduler.schedule(state, setDisposable);
11849 } else {
11850 setDisposable(null, state);
11851 }
11852 return ado;
11853 };
11854
11855 return AnonymousObservable;
11856
11857 }(Observable));
11858
11859 var AutoDetachObserver = (function (__super__) {
11860 inherits(AutoDetachObserver, __super__);
11861
11862 function AutoDetachObserver(observer) {
11863 __super__.call(this);
11864 this.observer = observer;
11865 this.m = new SingleAssignmentDisposable();
11866 }
11867
11868 var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
11869
11870 AutoDetachObserverPrototype.next = function (value) {
11871 var result = tryCatch(this.observer.onNext).call(this.observer, value);
11872 if (result === errorObj) {
11873 this.dispose();
11874 thrower(result.e);
11875 }
11876 };
11877
11878 AutoDetachObserverPrototype.error = function (err) {
11879 var result = tryCatch(this.observer.onError).call(this.observer, err);
11880 this.dispose();
11881 result === errorObj && thrower(result.e);
11882 };
11883
11884 AutoDetachObserverPrototype.completed = function () {
11885 var result = tryCatch(this.observer.onCompleted).call(this.observer);
11886 this.dispose();
11887 result === errorObj && thrower(result.e);
11888 };
11889
11890 AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
11891 AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
11892
11893 AutoDetachObserverPrototype.dispose = function () {
11894 __super__.prototype.dispose.call(this);
11895 this.m.dispose();
11896 };
11897
11898 return AutoDetachObserver;
11899 }(AbstractObserver));
11900
11901 var UnderlyingObservable = (function (__super__) {
11902 inherits(UnderlyingObservable, __super__);
11903 function UnderlyingObservable(m, u) {
11904 this._m = m;
11905 this._u = u;
11906 __super__.call(this);
11907 }
11908
11909 UnderlyingObservable.prototype.subscribeCore = function (o) {
11910 return new BinaryDisposable(this._m.getDisposable(), this._u.subscribe(o));
11911 };
11912
11913 return UnderlyingObservable;
11914 }(ObservableBase));
11915
11916 var GroupedObservable = (function (__super__) {
11917 inherits(GroupedObservable, __super__);
11918 function GroupedObservable(key, underlyingObservable, mergedDisposable) {
11919 __super__.call(this);
11920 this.key = key;
11921 this.underlyingObservable = !mergedDisposable ?
11922 underlyingObservable :
11923 new UnderlyingObservable(mergedDisposable, underlyingObservable);
11924 }
11925
11926 GroupedObservable.prototype._subscribe = function (o) {
11927 return this.underlyingObservable.subscribe(o);
11928 };
11929
11930 return GroupedObservable;
11931 }(Observable));
11932
11933 /**
11934 * Represents an object that is both an observable sequence as well as an observer.
11935 * Each notification is broadcasted to all subscribed observers.
11936 */
11937 var Subject = Rx.Subject = (function (__super__) {
11938 inherits(Subject, __super__);
11939 function Subject() {
11940 __super__.call(this);
11941 this.isDisposed = false;
11942 this.isStopped = false;
11943 this.observers = [];
11944 this.hasError = false;
11945 }
11946
11947 addProperties(Subject.prototype, Observer.prototype, {
11948 _subscribe: function (o) {
11949 checkDisposed(this);
11950 if (!this.isStopped) {
11951 this.observers.push(o);
11952 return new InnerSubscription(this, o);
11953 }
11954 if (this.hasError) {
11955 o.onError(this.error);
11956 return disposableEmpty;
11957 }
11958 o.onCompleted();
11959 return disposableEmpty;
11960 },
11961 /**
11962 * Indicates whether the subject has observers subscribed to it.
11963 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
11964 */
11965 hasObservers: function () { return this.observers.length > 0; },
11966 /**
11967 * Notifies all subscribed observers about the end of the sequence.
11968 */
11969 onCompleted: function () {
11970 checkDisposed(this);
11971 if (!this.isStopped) {
11972 this.isStopped = true;
11973 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
11974 os[i].onCompleted();
11975 }
11976
11977 this.observers.length = 0;
11978 }
11979 },
11980 /**
11981 * Notifies all subscribed observers about the exception.
11982 * @param {Mixed} error The exception to send to all observers.
11983 */
11984 onError: function (error) {
11985 checkDisposed(this);
11986 if (!this.isStopped) {
11987 this.isStopped = true;
11988 this.error = error;
11989 this.hasError = true;
11990 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
11991 os[i].onError(error);
11992 }
11993
11994 this.observers.length = 0;
11995 }
11996 },
11997 /**
11998 * Notifies all subscribed observers about the arrival of the specified element in the sequence.
11999 * @param {Mixed} value The value to send to all observers.
12000 */
12001 onNext: function (value) {
12002 checkDisposed(this);
12003 if (!this.isStopped) {
12004 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12005 os[i].onNext(value);
12006 }
12007 }
12008 },
12009 /**
12010 * Unsubscribe all observers and release resources.
12011 */
12012 dispose: function () {
12013 this.isDisposed = true;
12014 this.observers = null;
12015 }
12016 });
12017
12018 /**
12019 * Creates a subject from the specified observer and observable.
12020 * @param {Observer} observer The observer used to send messages to the subject.
12021 * @param {Observable} observable The observable used to subscribe to messages sent from the subject.
12022 * @returns {Subject} Subject implemented using the given observer and observable.
12023 */
12024 Subject.create = function (observer, observable) {
12025 return new AnonymousSubject(observer, observable);
12026 };
12027
12028 return Subject;
12029 }(Observable));
12030
12031 /**
12032 * Represents the result of an asynchronous operation.
12033 * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
12034 */
12035 var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
12036 inherits(AsyncSubject, __super__);
12037
12038 /**
12039 * Creates a subject that can only receive one value and that value is cached for all future observations.
12040 * @constructor
12041 */
12042 function AsyncSubject() {
12043 __super__.call(this);
12044 this.isDisposed = false;
12045 this.isStopped = false;
12046 this.hasValue = false;
12047 this.observers = [];
12048 this.hasError = false;
12049 }
12050
12051 addProperties(AsyncSubject.prototype, Observer.prototype, {
12052 _subscribe: function (o) {
12053 checkDisposed(this);
12054
12055 if (!this.isStopped) {
12056 this.observers.push(o);
12057 return new InnerSubscription(this, o);
12058 }
12059
12060 if (this.hasError) {
12061 o.onError(this.error);
12062 } else if (this.hasValue) {
12063 o.onNext(this.value);
12064 o.onCompleted();
12065 } else {
12066 o.onCompleted();
12067 }
12068
12069 return disposableEmpty;
12070 },
12071 /**
12072 * Indicates whether the subject has observers subscribed to it.
12073 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
12074 */
12075 hasObservers: function () {
12076 checkDisposed(this);
12077 return this.observers.length > 0;
12078 },
12079 /**
12080 * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
12081 */
12082 onCompleted: function () {
12083 var i, len;
12084 checkDisposed(this);
12085 if (!this.isStopped) {
12086 this.isStopped = true;
12087 var os = cloneArray(this.observers), len = os.length;
12088
12089 if (this.hasValue) {
12090 for (i = 0; i < len; i++) {
12091 var o = os[i];
12092 o.onNext(this.value);
12093 o.onCompleted();
12094 }
12095 } else {
12096 for (i = 0; i < len; i++) {
12097 os[i].onCompleted();
12098 }
12099 }
12100
12101 this.observers.length = 0;
12102 }
12103 },
12104 /**
12105 * Notifies all subscribed observers about the error.
12106 * @param {Mixed} error The Error to send to all observers.
12107 */
12108 onError: function (error) {
12109 checkDisposed(this);
12110 if (!this.isStopped) {
12111 this.isStopped = true;
12112 this.hasError = true;
12113 this.error = error;
12114
12115 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12116 os[i].onError(error);
12117 }
12118
12119 this.observers.length = 0;
12120 }
12121 },
12122 /**
12123 * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
12124 * @param {Mixed} value The value to store in the subject.
12125 */
12126 onNext: function (value) {
12127 checkDisposed(this);
12128 if (this.isStopped) { return; }
12129 this.value = value;
12130 this.hasValue = true;
12131 },
12132 /**
12133 * Unsubscribe all observers and release resources.
12134 */
12135 dispose: function () {
12136 this.isDisposed = true;
12137 this.observers = null;
12138 this.error = null;
12139 this.value = null;
12140 }
12141 });
12142
12143 return AsyncSubject;
12144 }(Observable));
12145
12146 var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
12147 inherits(AnonymousSubject, __super__);
12148 function AnonymousSubject(observer, observable) {
12149 this.observer = observer;
12150 this.observable = observable;
12151 __super__.call(this);
12152 }
12153
12154 addProperties(AnonymousSubject.prototype, Observer.prototype, {
12155 _subscribe: function (o) {
12156 return this.observable.subscribe(o);
12157 },
12158 onCompleted: function () {
12159 this.observer.onCompleted();
12160 },
12161 onError: function (error) {
12162 this.observer.onError(error);
12163 },
12164 onNext: function (value) {
12165 this.observer.onNext(value);
12166 }
12167 });
12168
12169 return AnonymousSubject;
12170 }(Observable));
12171
12172 /**
12173 * Represents a value that changes over time.
12174 * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
12175 */
12176 var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
12177 inherits(BehaviorSubject, __super__);
12178 function BehaviorSubject(value) {
12179 __super__.call(this);
12180 this.value = value;
12181 this.observers = [];
12182 this.isDisposed = false;
12183 this.isStopped = false;
12184 this.hasError = false;
12185 }
12186
12187 addProperties(BehaviorSubject.prototype, Observer.prototype, {
12188 _subscribe: function (o) {
12189 checkDisposed(this);
12190 if (!this.isStopped) {
12191 this.observers.push(o);
12192 o.onNext(this.value);
12193 return new InnerSubscription(this, o);
12194 }
12195 if (this.hasError) {
12196 o.onError(this.error);
12197 } else {
12198 o.onCompleted();
12199 }
12200 return disposableEmpty;
12201 },
12202 /**
12203 * Gets the current value or throws an exception.
12204 * Value is frozen after onCompleted is called.
12205 * After onError is called always throws the specified exception.
12206 * An exception is always thrown after dispose is called.
12207 * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
12208 */
12209 getValue: function () {
12210 checkDisposed(this);
12211 if (this.hasError) { thrower(this.error); }
12212 return this.value;
12213 },
12214 /**
12215 * Indicates whether the subject has observers subscribed to it.
12216 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
12217 */
12218 hasObservers: function () { return this.observers.length > 0; },
12219 /**
12220 * Notifies all subscribed observers about the end of the sequence.
12221 */
12222 onCompleted: function () {
12223 checkDisposed(this);
12224 if (this.isStopped) { return; }
12225 this.isStopped = true;
12226 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12227 os[i].onCompleted();
12228 }
12229
12230 this.observers.length = 0;
12231 },
12232 /**
12233 * Notifies all subscribed observers about the exception.
12234 * @param {Mixed} error The exception to send to all observers.
12235 */
12236 onError: function (error) {
12237 checkDisposed(this);
12238 if (this.isStopped) { return; }
12239 this.isStopped = true;
12240 this.hasError = true;
12241 this.error = error;
12242
12243 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12244 os[i].onError(error);
12245 }
12246
12247 this.observers.length = 0;
12248 },
12249 /**
12250 * Notifies all subscribed observers about the arrival of the specified element in the sequence.
12251 * @param {Mixed} value The value to send to all observers.
12252 */
12253 onNext: function (value) {
12254 checkDisposed(this);
12255 if (this.isStopped) { return; }
12256 this.value = value;
12257 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12258 os[i].onNext(value);
12259 }
12260 },
12261 /**
12262 * Unsubscribe all observers and release resources.
12263 */
12264 dispose: function () {
12265 this.isDisposed = true;
12266 this.observers = null;
12267 this.value = null;
12268 this.error = null;
12269 }
12270 });
12271
12272 return BehaviorSubject;
12273 }(Observable));
12274
12275 /**
12276 * Represents an object that is both an observable sequence as well as an observer.
12277 * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
12278 */
12279 var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
12280
12281 var maxSafeInteger = Math.pow(2, 53) - 1;
12282
12283 function createRemovableDisposable(subject, observer) {
12284 return disposableCreate(function () {
12285 observer.dispose();
12286 !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
12287 });
12288 }
12289
12290 inherits(ReplaySubject, __super__);
12291
12292 /**
12293 * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
12294 * @param {Number} [bufferSize] Maximum element count of the replay buffer.
12295 * @param {Number} [windowSize] Maximum time length of the replay buffer.
12296 * @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
12297 */
12298 function ReplaySubject(bufferSize, windowSize, scheduler) {
12299 this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
12300 this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
12301 this.scheduler = scheduler || currentThreadScheduler;
12302 this.q = [];
12303 this.observers = [];
12304 this.isStopped = false;
12305 this.isDisposed = false;
12306 this.hasError = false;
12307 this.error = null;
12308 __super__.call(this);
12309 }
12310
12311 addProperties(ReplaySubject.prototype, Observer.prototype, {
12312 _subscribe: function (o) {
12313 checkDisposed(this);
12314 var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so);
12315
12316 this._trim(this.scheduler.now());
12317 this.observers.push(so);
12318
12319 for (var i = 0, len = this.q.length; i < len; i++) {
12320 so.onNext(this.q[i].value);
12321 }
12322
12323 if (this.hasError) {
12324 so.onError(this.error);
12325 } else if (this.isStopped) {
12326 so.onCompleted();
12327 }
12328
12329 so.ensureActive();
12330 return subscription;
12331 },
12332 /**
12333 * Indicates whether the subject has observers subscribed to it.
12334 * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
12335 */
12336 hasObservers: function () {
12337 return this.observers.length > 0;
12338 },
12339 _trim: function (now) {
12340 while (this.q.length > this.bufferSize) {
12341 this.q.shift();
12342 }
12343 while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
12344 this.q.shift();
12345 }
12346 },
12347 /**
12348 * Notifies all subscribed observers about the arrival of the specified element in the sequence.
12349 * @param {Mixed} value The value to send to all observers.
12350 */
12351 onNext: function (value) {
12352 checkDisposed(this);
12353 if (this.isStopped) { return; }
12354 var now = this.scheduler.now();
12355 this.q.push({ interval: now, value: value });
12356 this._trim(now);
12357
12358 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12359 var observer = os[i];
12360 observer.onNext(value);
12361 observer.ensureActive();
12362 }
12363 },
12364 /**
12365 * Notifies all subscribed observers about the exception.
12366 * @param {Mixed} error The exception to send to all observers.
12367 */
12368 onError: function (error) {
12369 checkDisposed(this);
12370 if (this.isStopped) { return; }
12371 this.isStopped = true;
12372 this.error = error;
12373 this.hasError = true;
12374 var now = this.scheduler.now();
12375 this._trim(now);
12376 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12377 var observer = os[i];
12378 observer.onError(error);
12379 observer.ensureActive();
12380 }
12381 this.observers.length = 0;
12382 },
12383 /**
12384 * Notifies all subscribed observers about the end of the sequence.
12385 */
12386 onCompleted: function () {
12387 checkDisposed(this);
12388 if (this.isStopped) { return; }
12389 this.isStopped = true;
12390 var now = this.scheduler.now();
12391 this._trim(now);
12392 for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
12393 var observer = os[i];
12394 observer.onCompleted();
12395 observer.ensureActive();
12396 }
12397 this.observers.length = 0;
12398 },
12399 /**
12400 * Unsubscribe all observers and release resources.
12401 */
12402 dispose: function () {
12403 this.isDisposed = true;
12404 this.observers = null;
12405 }
12406 });
12407
12408 return ReplaySubject;
12409 }(Observable));
12410
12411 /**
12412 * Used to pause and resume streams.
12413 */
12414 Rx.Pauser = (function (__super__) {
12415 inherits(Pauser, __super__);
12416 function Pauser() {
12417 __super__.call(this);
12418 }
12419
12420 /**
12421 * Pauses the underlying sequence.
12422 */
12423 Pauser.prototype.pause = function () { this.onNext(false); };
12424
12425 /**
12426 * Resumes the underlying sequence.
12427 */
12428 Pauser.prototype.resume = function () { this.onNext(true); };
12429
12430 return Pauser;
12431 }(Subject));
12432
12433 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
12434 root.Rx = Rx;
12435
12436 define(function() {
12437 return Rx;
12438 });
12439 } else if (freeExports && freeModule) {
12440 // in Node.js or RingoJS
12441 if (moduleExports) {
12442 (freeModule.exports = Rx).Rx = Rx;
12443 } else {
12444 freeExports.Rx = Rx;
12445 }
12446 } else {
12447 // in a browser or Rhino
12448 root.Rx = Rx;
12449 }
12450
12451 // All code before this point will be filtered from stack traces.
12452 var rEndingLine = captureLine();
12453
12454}.call(this));