UNPKG

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