rxjs-rails 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (39) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +3 -0
  3. data/LICENSE +19 -0
  4. data/README.md +14 -0
  5. data/lib/rxjs/rails/engine.rb +7 -0
  6. data/lib/rxjs/rails/railtie.rb +7 -0
  7. data/lib/rxjs/rails/version.rb +7 -0
  8. data/lib/rxjs/rails.rb +8 -0
  9. data/lib/rxjs.rb +1 -0
  10. data/rxjs-rails.gemspec +22 -0
  11. data/vendor/assets/javascripts/rx.aggregates.js +687 -0
  12. data/vendor/assets/javascripts/rx.aggregates.min.js +1 -0
  13. data/vendor/assets/javascripts/rx.async.compat.js +376 -0
  14. data/vendor/assets/javascripts/rx.async.compat.min.js +1 -0
  15. data/vendor/assets/javascripts/rx.async.js +306 -0
  16. data/vendor/assets/javascripts/rx.async.min.js +1 -0
  17. data/vendor/assets/javascripts/rx.binding.js +561 -0
  18. data/vendor/assets/javascripts/rx.binding.min.js +1 -0
  19. data/vendor/assets/javascripts/rx.coincidence.js +691 -0
  20. data/vendor/assets/javascripts/rx.coincidence.min.js +1 -0
  21. data/vendor/assets/javascripts/rx.compat.js +4351 -0
  22. data/vendor/assets/javascripts/rx.compat.min.js +2 -0
  23. data/vendor/assets/javascripts/rx.experimental.js +453 -0
  24. data/vendor/assets/javascripts/rx.experimental.min.js +1 -0
  25. data/vendor/assets/javascripts/rx.joinpatterns.js +418 -0
  26. data/vendor/assets/javascripts/rx.joinpatterns.min.js +1 -0
  27. data/vendor/assets/javascripts/rx.lite.compat.js +5188 -0
  28. data/vendor/assets/javascripts/rx.lite.compat.min.js +2 -0
  29. data/vendor/assets/javascripts/rx.lite.js +5000 -0
  30. data/vendor/assets/javascripts/rx.lite.min.js +2 -0
  31. data/vendor/assets/javascripts/rx.min.js +2 -0
  32. data/vendor/assets/javascripts/rx.node.js +143 -0
  33. data/vendor/assets/javascripts/rx.testing.js +503 -0
  34. data/vendor/assets/javascripts/rx.testing.min.js +1 -0
  35. data/vendor/assets/javascripts/rx.time.js +1166 -0
  36. data/vendor/assets/javascripts/rx.time.min.js +1 -0
  37. data/vendor/assets/javascripts/rx.virtualtime.js +336 -0
  38. data/vendor/assets/javascripts/rx.virtualtime.min.js +1 -0
  39. metadata +101 -0
@@ -0,0 +1,4351 @@
1
+ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
+
3
+ ;(function (undefined) {
4
+
5
+ var objectTypes = {
6
+ 'boolean': false,
7
+ 'function': true,
8
+ 'object': true,
9
+ 'number': false,
10
+ 'string': false,
11
+ 'undefined': false
12
+ };
13
+
14
+ var root = (objectTypes[typeof window] && window) || this,
15
+ freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
16
+ freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
17
+ moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
18
+ freeGlobal = objectTypes[typeof global] && global;
19
+
20
+ if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
21
+ root = freeGlobal;
22
+ }
23
+
24
+ var Rx = { Internals: {} };
25
+
26
+ // Defaults
27
+ function noop() { }
28
+ function identity(x) { return x; }
29
+ var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }());
30
+ function defaultComparer(x, y) { return isEqual(x, y); }
31
+ function defaultSubComparer(x, y) { return x - y; }
32
+ function defaultKeySerializer(x) { return x.toString(); }
33
+ function defaultError(err) { throw err; }
34
+
35
+ // Errors
36
+ var sequenceContainsNoElements = 'Sequence contains no elements.';
37
+ var argumentOutOfRange = 'Argument out of range';
38
+ var objectDisposed = 'Object has been disposed';
39
+ function checkDisposed() {
40
+ if (this.isDisposed) {
41
+ throw new Error(objectDisposed);
42
+ }
43
+ }
44
+
45
+ /** Used to determine if values are of the language type Object */
46
+ var objectTypes = {
47
+ 'boolean': false,
48
+ 'function': true,
49
+ 'object': true,
50
+ 'number': false,
51
+ 'string': false,
52
+ 'undefined': false
53
+ };
54
+
55
+ /** `Object#toString` result shortcuts */
56
+ var argsClass = '[object Arguments]',
57
+ arrayClass = '[object Array]',
58
+ boolClass = '[object Boolean]',
59
+ dateClass = '[object Date]',
60
+ errorClass = '[object Error]',
61
+ funcClass = '[object Function]',
62
+ numberClass = '[object Number]',
63
+ objectClass = '[object Object]',
64
+ regexpClass = '[object RegExp]',
65
+ stringClass = '[object String]';
66
+
67
+ var toString = Object.prototype.toString,
68
+ hasOwnProperty = Object.prototype.hasOwnProperty,
69
+ supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
70
+ suportNodeClass;
71
+
72
+ try {
73
+ suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
74
+ } catch(e) {
75
+ suportNodeClass = true;
76
+ }
77
+
78
+ function isNode(value) {
79
+ // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
80
+ // methods that are `typeof` "string" and still can coerce nodes to strings
81
+ return typeof value.toString != 'function' && typeof (value + '') == 'string';
82
+ }
83
+
84
+ function isArguments(value) {
85
+ return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
86
+ }
87
+
88
+ // fallback for browsers that can't detect `arguments` objects by [[Class]]
89
+ if (!supportsArgsClass) {
90
+ isArguments = function(value) {
91
+ return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
92
+ };
93
+ }
94
+
95
+ function isFunction(value) {
96
+ return typeof value == 'function';
97
+ }
98
+
99
+ // fallback for older versions of Chrome and Safari
100
+ if (isFunction(/x/)) {
101
+ isFunction = function(value) {
102
+ return typeof value == 'function' && toString.call(value) == funcClass;
103
+ };
104
+ }
105
+
106
+ var isEqual = Rx.Internals.isEqual = function (x, y) {
107
+ return deepEquals(x, y, [], []);
108
+ };
109
+
110
+ /** @private
111
+ * Used for deep comparison
112
+ **/
113
+ function deepEquals(a, b, stackA, stackB) {
114
+ var result;
115
+ // exit early for identical values
116
+ if (a === b) {
117
+ // treat `+0` vs. `-0` as not equal
118
+ return a !== 0 || (1 / a == 1 / b);
119
+ }
120
+ var type = typeof a,
121
+ otherType = typeof b;
122
+
123
+ // exit early for unlike primitive values
124
+ if (a === a &&
125
+ !(a && objectTypes[type]) &&
126
+ !(b && objectTypes[otherType])) {
127
+ return false;
128
+ }
129
+
130
+ // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
131
+ // http://es5.github.io/#x15.3.4.4
132
+ if (a == null || b == null) {
133
+ return a === b;
134
+ }
135
+ // compare [[Class]] names
136
+ var className = toString.call(a),
137
+ otherClass = toString.call(b);
138
+
139
+ if (className == argsClass) {
140
+ className = objectClass;
141
+ }
142
+ if (otherClass == argsClass) {
143
+ otherClass = objectClass;
144
+ }
145
+ if (className != otherClass) {
146
+ return false;
147
+ }
148
+
149
+ switch (className) {
150
+ case boolClass:
151
+ case dateClass:
152
+ // coerce dates and booleans to numbers, dates to milliseconds and booleans
153
+ // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
154
+ return +a == +b;
155
+
156
+ case numberClass:
157
+ // treat `NaN` vs. `NaN` as equal
158
+ return (a != +a)
159
+ ? b != +b
160
+ // but treat `+0` vs. `-0` as not equal
161
+ : (a == 0 ? (1 / a == 1 / b) : a == +b);
162
+
163
+ case regexpClass:
164
+ case stringClass:
165
+ // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
166
+ // treat string primitives and their corresponding object instances as equal
167
+ return a == String(b);
168
+ }
169
+
170
+ var isArr = className == arrayClass;
171
+ if (!isArr) {
172
+
173
+ // exit for functions and DOM nodes
174
+ if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
175
+ return false;
176
+ }
177
+
178
+ // in older versions of Opera, `arguments` objects have `Array` constructors
179
+ var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
180
+ ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
181
+
182
+ // non `Object` object instances with different constructors are not equal
183
+ if (ctorA != ctorB && !(
184
+ isFunction(ctorA) && ctorA instanceof ctorA &&
185
+ isFunction(ctorB) && ctorB instanceof ctorB
186
+ )) {
187
+ return false;
188
+ }
189
+ }
190
+
191
+ // assume cyclic structures are equal
192
+ // the algorithm for detecting cyclic structures is adapted from ES 5.1
193
+ // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
194
+ var length = stackA.length;
195
+ while (length--) {
196
+ if (stackA[length] == a) {
197
+ return stackB[length] == b;
198
+ }
199
+ }
200
+
201
+ var size = 0;
202
+ result = true;
203
+
204
+ // add `a` and `b` to the stack of traversed objects
205
+ stackA.push(a);
206
+ stackB.push(b);
207
+
208
+ // recursively compare objects and arrays (susceptible to call stack limits)
209
+ if (isArr) {
210
+ length = a.length;
211
+ size = b.length;
212
+
213
+ // compare lengths to determine if a deep comparison is necessary
214
+ result = size == a.length;
215
+ // deep compare the contents, ignoring non-numeric properties
216
+ while (size--) {
217
+ var index = length,
218
+ value = b[size];
219
+
220
+ if (!(result = deepEquals(a[size], value, stackA, stackB))) {
221
+ break;
222
+ }
223
+ }
224
+
225
+ return result;
226
+ }
227
+
228
+ // deep compare each object
229
+ for(var key in b) {
230
+ if (hasOwnProperty.call(b, key)) {
231
+ // count properties and deep compare each property value
232
+ size++;
233
+ return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
234
+ }
235
+ }
236
+
237
+ if (result) {
238
+ // ensure both objects have the same number of properties
239
+ for (var key in a) {
240
+ if (hasOwnProperty.call(a, key)) {
241
+ // `size` will be `-1` if `a` has more properties than `b`
242
+ return (result = --size > -1);
243
+ }
244
+ }
245
+ }
246
+ stackA.pop();
247
+ stackB.pop();
248
+
249
+ return result;
250
+ }
251
+ var slice = Array.prototype.slice;
252
+ function argsOrArray(args, idx) {
253
+ return args.length === 1 && Array.isArray(args[idx]) ?
254
+ args[idx] :
255
+ slice.call(args);
256
+ }
257
+ var hasProp = {}.hasOwnProperty;
258
+
259
+ /** @private */
260
+ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
261
+ function __() { this.constructor = child; }
262
+ __.prototype = parent.prototype;
263
+ child.prototype = new __();
264
+ };
265
+
266
+ /** @private */
267
+ var addProperties = Rx.Internals.addProperties = function (obj) {
268
+ var sources = slice.call(arguments, 1);
269
+ for (var i = 0, len = sources.length; i < len; i++) {
270
+ var source = sources[i];
271
+ for (var prop in source) {
272
+ obj[prop] = source[prop];
273
+ }
274
+ }
275
+ };
276
+
277
+ // Rx Utils
278
+ var addRef = Rx.Internals.addRef = function (xs, r) {
279
+ return new AnonymousObservable(function (observer) {
280
+ return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
281
+ });
282
+ };
283
+
284
+ // Collection polyfills
285
+ function arrayInitialize(count, factory) {
286
+ var a = new Array(count);
287
+ for (var i = 0; i < count; i++) {
288
+ a[i] = factory();
289
+ }
290
+ return a;
291
+ }
292
+
293
+ // Utilities
294
+ if (!Function.prototype.bind) {
295
+ Function.prototype.bind = function (that) {
296
+ var target = this,
297
+ args = slice.call(arguments, 1);
298
+ var bound = function () {
299
+ if (this instanceof bound) {
300
+ function F() { }
301
+ F.prototype = target.prototype;
302
+ var self = new F();
303
+ var result = target.apply(self, args.concat(slice.call(arguments)));
304
+ if (Object(result) === result) {
305
+ return result;
306
+ }
307
+ return self;
308
+ } else {
309
+ return target.apply(that, args.concat(slice.call(arguments)));
310
+ }
311
+ };
312
+
313
+ return bound;
314
+ };
315
+ }
316
+
317
+ var boxedString = Object("a"),
318
+ splitString = boxedString[0] != "a" || !(0 in boxedString);
319
+ if (!Array.prototype.every) {
320
+ Array.prototype.every = function every(fun /*, thisp */) {
321
+ var object = Object(this),
322
+ self = splitString && {}.toString.call(this) == "[object String]" ?
323
+ this.split("") :
324
+ object,
325
+ length = self.length >>> 0,
326
+ thisp = arguments[1];
327
+
328
+ if ({}.toString.call(fun) != "[object Function]") {
329
+ throw new TypeError(fun + " is not a function");
330
+ }
331
+
332
+ for (var i = 0; i < length; i++) {
333
+ if (i in self && !fun.call(thisp, self[i], i, object)) {
334
+ return false;
335
+ }
336
+ }
337
+ return true;
338
+ };
339
+ }
340
+
341
+ if (!Array.prototype.map) {
342
+ Array.prototype.map = function map(fun /*, thisp*/) {
343
+ var object = Object(this),
344
+ self = splitString && {}.toString.call(this) == "[object String]" ?
345
+ this.split("") :
346
+ object,
347
+ length = self.length >>> 0,
348
+ result = Array(length),
349
+ thisp = arguments[1];
350
+
351
+ if ({}.toString.call(fun) != "[object Function]") {
352
+ throw new TypeError(fun + " is not a function");
353
+ }
354
+
355
+ for (var i = 0; i < length; i++) {
356
+ if (i in self)
357
+ result[i] = fun.call(thisp, self[i], i, object);
358
+ }
359
+ return result;
360
+ };
361
+ }
362
+
363
+ if (!Array.prototype.filter) {
364
+ Array.prototype.filter = function (predicate) {
365
+ var results = [], item, t = new Object(this);
366
+ for (var i = 0, len = t.length >>> 0; i < len; i++) {
367
+ item = t[i];
368
+ if (i in t && predicate.call(arguments[1], item, i, t)) {
369
+ results.push(item);
370
+ }
371
+ }
372
+ return results;
373
+ };
374
+ }
375
+
376
+ if (!Array.isArray) {
377
+ Array.isArray = function (arg) {
378
+ return Object.prototype.toString.call(arg) == '[object Array]';
379
+ };
380
+ }
381
+
382
+ if (!Array.prototype.indexOf) {
383
+ Array.prototype.indexOf = function indexOf(searchElement) {
384
+ var t = Object(this);
385
+ var len = t.length >>> 0;
386
+ if (len === 0) {
387
+ return -1;
388
+ }
389
+ var n = 0;
390
+ if (arguments.length > 1) {
391
+ n = Number(arguments[1]);
392
+ if (n !== n) {
393
+ n = 0;
394
+ } else if (n !== 0 && n != Infinity && n !== -Infinity) {
395
+ n = (n > 0 || -1) * Math.floor(Math.abs(n));
396
+ }
397
+ }
398
+ if (n >= len) {
399
+ return -1;
400
+ }
401
+ var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
402
+ for (; k < len; k++) {
403
+ if (k in t && t[k] === searchElement) {
404
+ return k;
405
+ }
406
+ }
407
+ return -1;
408
+ };
409
+ }
410
+
411
+ // Collections
412
+ var IndexedItem = function (id, value) {
413
+ this.id = id;
414
+ this.value = value;
415
+ };
416
+
417
+ IndexedItem.prototype.compareTo = function (other) {
418
+ var c = this.value.compareTo(other.value);
419
+ if (c === 0) {
420
+ c = this.id - other.id;
421
+ }
422
+ return c;
423
+ };
424
+
425
+ // Priority Queue for Scheduling
426
+ var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) {
427
+ this.items = new Array(capacity);
428
+ this.length = 0;
429
+ };
430
+
431
+ var priorityProto = PriorityQueue.prototype;
432
+ priorityProto.isHigherPriority = function (left, right) {
433
+ return this.items[left].compareTo(this.items[right]) < 0;
434
+ };
435
+
436
+ priorityProto.percolate = function (index) {
437
+ if (index >= this.length || index < 0) {
438
+ return;
439
+ }
440
+ var parent = index - 1 >> 1;
441
+ if (parent < 0 || parent === index) {
442
+ return;
443
+ }
444
+ if (this.isHigherPriority(index, parent)) {
445
+ var temp = this.items[index];
446
+ this.items[index] = this.items[parent];
447
+ this.items[parent] = temp;
448
+ this.percolate(parent);
449
+ }
450
+ };
451
+
452
+ priorityProto.heapify = function (index) {
453
+ if (index === undefined) {
454
+ index = 0;
455
+ }
456
+ if (index >= this.length || index < 0) {
457
+ return;
458
+ }
459
+ var left = 2 * index + 1,
460
+ right = 2 * index + 2,
461
+ first = index;
462
+ if (left < this.length && this.isHigherPriority(left, first)) {
463
+ first = left;
464
+ }
465
+ if (right < this.length && this.isHigherPriority(right, first)) {
466
+ first = right;
467
+ }
468
+ if (first !== index) {
469
+ var temp = this.items[index];
470
+ this.items[index] = this.items[first];
471
+ this.items[first] = temp;
472
+ this.heapify(first);
473
+ }
474
+ };
475
+
476
+ priorityProto.peek = function () { return this.items[0].value; };
477
+
478
+ priorityProto.removeAt = function (index) {
479
+ this.items[index] = this.items[--this.length];
480
+ delete this.items[this.length];
481
+ this.heapify();
482
+ };
483
+
484
+ priorityProto.dequeue = function () {
485
+ var result = this.peek();
486
+ this.removeAt(0);
487
+ return result;
488
+ };
489
+
490
+ priorityProto.enqueue = function (item) {
491
+ var index = this.length++;
492
+ this.items[index] = new IndexedItem(PriorityQueue.count++, item);
493
+ this.percolate(index);
494
+ };
495
+
496
+ priorityProto.remove = function (item) {
497
+ for (var i = 0; i < this.length; i++) {
498
+ if (this.items[i].value === item) {
499
+ this.removeAt(i);
500
+ return true;
501
+ }
502
+ }
503
+ return false;
504
+ };
505
+ PriorityQueue.count = 0;
506
+ /**
507
+ * Represents a group of disposable resources that are disposed together.
508
+ * @constructor
509
+ */
510
+ var CompositeDisposable = Rx.CompositeDisposable = function () {
511
+ this.disposables = argsOrArray(arguments, 0);
512
+ this.isDisposed = false;
513
+ this.length = this.disposables.length;
514
+ };
515
+
516
+ var CompositeDisposablePrototype = CompositeDisposable.prototype;
517
+
518
+ /**
519
+ * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
520
+ * @param {Mixed} item Disposable to add.
521
+ */
522
+ CompositeDisposablePrototype.add = function (item) {
523
+ if (this.isDisposed) {
524
+ item.dispose();
525
+ } else {
526
+ this.disposables.push(item);
527
+ this.length++;
528
+ }
529
+ };
530
+
531
+ /**
532
+ * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
533
+ * @param {Mixed} item Disposable to remove.
534
+ * @returns {Boolean} true if found; false otherwise.
535
+ */
536
+ CompositeDisposablePrototype.remove = function (item) {
537
+ var shouldDispose = false;
538
+ if (!this.isDisposed) {
539
+ var idx = this.disposables.indexOf(item);
540
+ if (idx !== -1) {
541
+ shouldDispose = true;
542
+ this.disposables.splice(idx, 1);
543
+ this.length--;
544
+ item.dispose();
545
+ }
546
+
547
+ }
548
+ return shouldDispose;
549
+ };
550
+
551
+ /**
552
+ * Disposes all disposables in the group and removes them from the group.
553
+ */
554
+ CompositeDisposablePrototype.dispose = function () {
555
+ if (!this.isDisposed) {
556
+ this.isDisposed = true;
557
+ var currentDisposables = this.disposables.slice(0);
558
+ this.disposables = [];
559
+ this.length = 0;
560
+
561
+ for (var i = 0, len = currentDisposables.length; i < len; i++) {
562
+ currentDisposables[i].dispose();
563
+ }
564
+ }
565
+ };
566
+
567
+ /**
568
+ * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
569
+ */
570
+ CompositeDisposablePrototype.clear = function () {
571
+ var currentDisposables = this.disposables.slice(0);
572
+ this.disposables = [];
573
+ this.length = 0;
574
+ for (var i = 0, len = currentDisposables.length; i < len; i++) {
575
+ currentDisposables[i].dispose();
576
+ }
577
+ };
578
+
579
+ /**
580
+ * Determines whether the CompositeDisposable contains a specific disposable.
581
+ * @param {Mixed} item Disposable to search for.
582
+ * @returns {Boolean} true if the disposable was found; otherwise, false.
583
+ */
584
+ CompositeDisposablePrototype.contains = function (item) {
585
+ return this.disposables.indexOf(item) !== -1;
586
+ };
587
+
588
+ /**
589
+ * Converts the existing CompositeDisposable to an array of disposables
590
+ * @returns {Array} An array of disposable objects.
591
+ */
592
+ CompositeDisposablePrototype.toArray = function () {
593
+ return this.disposables.slice(0);
594
+ };
595
+
596
+ /**
597
+ * Provides a set of static methods for creating Disposables.
598
+ *
599
+ * @constructor
600
+ * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
601
+ */
602
+ var Disposable = Rx.Disposable = function (action) {
603
+ this.isDisposed = false;
604
+ this.action = action || noop;
605
+ };
606
+
607
+ /** Performs the task of cleaning up resources. */
608
+ Disposable.prototype.dispose = function () {
609
+ if (!this.isDisposed) {
610
+ this.action();
611
+ this.isDisposed = true;
612
+ }
613
+ };
614
+
615
+ /**
616
+ * Creates a disposable object that invokes the specified action when disposed.
617
+ * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
618
+ * @return {Disposable} The disposable object that runs the given action upon disposal.
619
+ */
620
+ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
621
+
622
+ /**
623
+ * Gets the disposable that does nothing when disposed.
624
+ */
625
+ var disposableEmpty = Disposable.empty = { dispose: noop };
626
+
627
+ var BooleanDisposable = (function () {
628
+ function BooleanDisposable (isSingle) {
629
+ this.isSingle = isSingle;
630
+ this.isDisposed = false;
631
+ this.current = null;
632
+ }
633
+
634
+ var booleanDisposablePrototype = BooleanDisposable.prototype;
635
+
636
+ /**
637
+ * Gets the underlying disposable.
638
+ * @return The underlying disposable.
639
+ */
640
+ booleanDisposablePrototype.getDisposable = function () {
641
+ return this.current;
642
+ };
643
+
644
+ /**
645
+ * Sets the underlying disposable.
646
+ * @param {Disposable} value The new underlying disposable.
647
+ */
648
+ booleanDisposablePrototype.setDisposable = function (value) {
649
+ if (this.current && this.isSingle) {
650
+ throw new Error('Disposable has already been assigned');
651
+ }
652
+
653
+ var shouldDispose = this.isDisposed, old;
654
+ if (!shouldDispose) {
655
+ old = this.current;
656
+ this.current = value;
657
+ }
658
+ if (old) {
659
+ old.dispose();
660
+ }
661
+ if (shouldDispose && value) {
662
+ value.dispose();
663
+ }
664
+ };
665
+
666
+ /**
667
+ * Disposes the underlying disposable as well as all future replacements.
668
+ */
669
+ booleanDisposablePrototype.dispose = function () {
670
+ var old;
671
+ if (!this.isDisposed) {
672
+ this.isDisposed = true;
673
+ old = this.current;
674
+ this.current = null;
675
+ }
676
+ if (old) {
677
+ old.dispose();
678
+ }
679
+ };
680
+
681
+ return BooleanDisposable;
682
+ }());
683
+
684
+ /**
685
+ * Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
686
+ * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
687
+ */
688
+ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
689
+ inherits(SingleAssignmentDisposable, super_);
690
+
691
+ function SingleAssignmentDisposable() {
692
+ super_.call(this, true);
693
+ }
694
+
695
+ return SingleAssignmentDisposable;
696
+ }(BooleanDisposable));
697
+
698
+ /**
699
+ * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
700
+ */
701
+ var SerialDisposable = Rx.SerialDisposable = (function (super_) {
702
+ inherits(SerialDisposable, super_);
703
+
704
+ function SerialDisposable() {
705
+ super_.call(this, false);
706
+ }
707
+
708
+ return SerialDisposable;
709
+ }(BooleanDisposable));
710
+
711
+ /**
712
+ * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
713
+ */
714
+ var RefCountDisposable = Rx.RefCountDisposable = (function () {
715
+
716
+ function InnerDisposable(disposable) {
717
+ this.disposable = disposable;
718
+ this.disposable.count++;
719
+ this.isInnerDisposed = false;
720
+ }
721
+
722
+ InnerDisposable.prototype.dispose = function () {
723
+ if (!this.disposable.isDisposed) {
724
+ if (!this.isInnerDisposed) {
725
+ this.isInnerDisposed = true;
726
+ this.disposable.count--;
727
+ if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
728
+ this.disposable.isDisposed = true;
729
+ this.disposable.underlyingDisposable.dispose();
730
+ }
731
+ }
732
+ }
733
+ };
734
+
735
+ /**
736
+ * Initializes a new instance of the RefCountDisposable with the specified disposable.
737
+ * @constructor
738
+ * @param {Disposable} disposable Underlying disposable.
739
+ */
740
+ function RefCountDisposable(disposable) {
741
+ this.underlyingDisposable = disposable;
742
+ this.isDisposed = false;
743
+ this.isPrimaryDisposed = false;
744
+ this.count = 0;
745
+ }
746
+
747
+ /**
748
+ * Disposes the underlying disposable only when all dependent disposables have been disposed
749
+ */
750
+ RefCountDisposable.prototype.dispose = function () {
751
+ if (!this.isDisposed) {
752
+ if (!this.isPrimaryDisposed) {
753
+ this.isPrimaryDisposed = true;
754
+ if (this.count === 0) {
755
+ this.isDisposed = true;
756
+ this.underlyingDisposable.dispose();
757
+ }
758
+ }
759
+ }
760
+ };
761
+
762
+ /**
763
+ * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
764
+ * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
765
+ */
766
+ RefCountDisposable.prototype.getDisposable = function () {
767
+ return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
768
+ };
769
+
770
+ return RefCountDisposable;
771
+ })();
772
+
773
+ function ScheduledDisposable(scheduler, disposable) {
774
+ this.scheduler = scheduler;
775
+ this.disposable = disposable;
776
+ this.isDisposed = false;
777
+ }
778
+
779
+ ScheduledDisposable.prototype.dispose = function () {
780
+ var parent = this;
781
+ this.scheduler.schedule(function () {
782
+ if (!parent.isDisposed) {
783
+ parent.isDisposed = true;
784
+ parent.disposable.dispose();
785
+ }
786
+ });
787
+ };
788
+
789
+ var ScheduledItem = Rx.Internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
790
+ this.scheduler = scheduler;
791
+ this.state = state;
792
+ this.action = action;
793
+ this.dueTime = dueTime;
794
+ this.comparer = comparer || defaultSubComparer;
795
+ this.disposable = new SingleAssignmentDisposable();
796
+ }
797
+
798
+ ScheduledItem.prototype.invoke = function () {
799
+ this.disposable.setDisposable(this.invokeCore());
800
+ };
801
+
802
+ ScheduledItem.prototype.compareTo = function (other) {
803
+ return this.comparer(this.dueTime, other.dueTime);
804
+ };
805
+
806
+ ScheduledItem.prototype.isCancelled = function () {
807
+ return this.disposable.isDisposed;
808
+ };
809
+
810
+ ScheduledItem.prototype.invokeCore = function () {
811
+ return this.action(this.scheduler, this.state);
812
+ };
813
+
814
+ /** Provides a set of static properties to access commonly used schedulers. */
815
+ var Scheduler = Rx.Scheduler = (function () {
816
+
817
+ /**
818
+ * @constructor
819
+ * @private
820
+ */
821
+ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
822
+ this.now = now;
823
+ this._schedule = schedule;
824
+ this._scheduleRelative = scheduleRelative;
825
+ this._scheduleAbsolute = scheduleAbsolute;
826
+ }
827
+
828
+ function invokeRecImmediate(scheduler, pair) {
829
+ var state = pair.first, action = pair.second, group = new CompositeDisposable(),
830
+ recursiveAction = function (state1) {
831
+ action(state1, function (state2) {
832
+ var isAdded = false, isDone = false,
833
+ d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
834
+ if (isAdded) {
835
+ group.remove(d);
836
+ } else {
837
+ isDone = true;
838
+ }
839
+ recursiveAction(state3);
840
+ return disposableEmpty;
841
+ });
842
+ if (!isDone) {
843
+ group.add(d);
844
+ isAdded = true;
845
+ }
846
+ });
847
+ };
848
+ recursiveAction(state);
849
+ return group;
850
+ }
851
+
852
+ function invokeRecDate(scheduler, pair, method) {
853
+ var state = pair.first, action = pair.second, group = new CompositeDisposable(),
854
+ recursiveAction = function (state1) {
855
+ action(state1, function (state2, dueTime1) {
856
+ var isAdded = false, isDone = false,
857
+ d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
858
+ if (isAdded) {
859
+ group.remove(d);
860
+ } else {
861
+ isDone = true;
862
+ }
863
+ recursiveAction(state3);
864
+ return disposableEmpty;
865
+ });
866
+ if (!isDone) {
867
+ group.add(d);
868
+ isAdded = true;
869
+ }
870
+ });
871
+ };
872
+ recursiveAction(state);
873
+ return group;
874
+ }
875
+
876
+ function invokeAction(scheduler, action) {
877
+ action();
878
+ return disposableEmpty;
879
+ }
880
+
881
+ var schedulerProto = Scheduler.prototype;
882
+
883
+ /**
884
+ * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
885
+ * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
886
+ * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
887
+ */
888
+ schedulerProto.catchException = schedulerProto['catch'] = function (handler) {
889
+ return new CatchScheduler(this, handler);
890
+ };
891
+
892
+ /**
893
+ * 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.
894
+ * @param {Number} period Period for running the work periodically.
895
+ * @param {Function} action Action to be executed.
896
+ * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
897
+ */
898
+ schedulerProto.schedulePeriodic = function (period, action) {
899
+ return this.schedulePeriodicWithState(null, period, function () {
900
+ action();
901
+ });
902
+ };
903
+
904
+ /**
905
+ * 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.
906
+ * @param {Mixed} state Initial state passed to the action upon the first iteration.
907
+ * @param {Number} period Period for running the work periodically.
908
+ * @param {Function} action Action to be executed, potentially updating the state.
909
+ * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
910
+ */
911
+ schedulerProto.schedulePeriodicWithState = function (state, period, action) {
912
+ var s = state, id = setInterval(function () {
913
+ s = action(s);
914
+ }, period);
915
+ return disposableCreate(function () {
916
+ clearInterval(id);
917
+ });
918
+ };
919
+
920
+ /**
921
+ * Schedules an action to be executed.
922
+ * @param {Function} action Action to execute.
923
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
924
+ */
925
+ schedulerProto.schedule = function (action) {
926
+ return this._schedule(action, invokeAction);
927
+ };
928
+
929
+ /**
930
+ * Schedules an action to be executed.
931
+ * @param state State passed to the action to be executed.
932
+ * @param {Function} action Action to be executed.
933
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
934
+ */
935
+ schedulerProto.scheduleWithState = function (state, action) {
936
+ return this._schedule(state, action);
937
+ };
938
+
939
+ /**
940
+ * Schedules an action to be executed after the specified relative due time.
941
+ * @param {Function} action Action to execute.
942
+ * @param {Number} dueTime Relative time after which to execute the action.
943
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
944
+ */
945
+ schedulerProto.scheduleWithRelative = function (dueTime, action) {
946
+ return this._scheduleRelative(action, dueTime, invokeAction);
947
+ };
948
+
949
+ /**
950
+ * Schedules an action to be executed after dueTime.
951
+ * @param state State passed to the action to be executed.
952
+ * @param {Function} action Action to be executed.
953
+ * @param {Number} dueTime Relative time after which to execute the action.
954
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
955
+ */
956
+ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
957
+ return this._scheduleRelative(state, dueTime, action);
958
+ };
959
+
960
+ /**
961
+ * Schedules an action to be executed at the specified absolute due time.
962
+ * @param {Function} action Action to execute.
963
+ * @param {Number} dueTime Absolute time at which to execute the action.
964
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
965
+ */
966
+ schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
967
+ return this._scheduleAbsolute(action, dueTime, invokeAction);
968
+ };
969
+
970
+ /**
971
+ * Schedules an action to be executed at dueTime.
972
+ * @param {Mixed} state State passed to the action to be executed.
973
+ * @param {Function} action Action to be executed.
974
+ * @param {Number}dueTime Absolute time at which to execute the action.
975
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
976
+ */
977
+ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
978
+ return this._scheduleAbsolute(state, dueTime, action);
979
+ };
980
+
981
+ /**
982
+ * Schedules an action to be executed recursively.
983
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
984
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
985
+ */
986
+ schedulerProto.scheduleRecursive = function (action) {
987
+ return this.scheduleRecursiveWithState(action, function (_action, self) {
988
+ _action(function () {
989
+ self(_action);
990
+ });
991
+ });
992
+ };
993
+
994
+ /**
995
+ * Schedules an action to be executed recursively.
996
+ * @param {Mixed} state State passed to the action to be executed.
997
+ * @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.
998
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
999
+ */
1000
+ schedulerProto.scheduleRecursiveWithState = function (state, action) {
1001
+ return this.scheduleWithState({ first: state, second: action }, function (s, p) {
1002
+ return invokeRecImmediate(s, p);
1003
+ });
1004
+ };
1005
+
1006
+ /**
1007
+ * Schedules an action to be executed recursively after a specified relative due time.
1008
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
1009
+ * @param {Number}dueTime Relative time after which to execute the action for the first time.
1010
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1011
+ */
1012
+ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
1013
+ return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
1014
+ _action(function (dt) {
1015
+ self(_action, dt);
1016
+ });
1017
+ });
1018
+ };
1019
+
1020
+ /**
1021
+ * Schedules an action to be executed recursively after a specified relative due time.
1022
+ * @param {Mixed} state State passed to the action to be executed.
1023
+ * @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.
1024
+ * @param {Number}dueTime Relative time after which to execute the action for the first time.
1025
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1026
+ */
1027
+ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
1028
+ return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
1029
+ return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
1030
+ });
1031
+ };
1032
+
1033
+ /**
1034
+ * Schedules an action to be executed recursively at a specified absolute due time.
1035
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
1036
+ * @param {Number}dueTime Absolute time at which to execute the action for the first time.
1037
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1038
+ */
1039
+ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
1040
+ return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
1041
+ _action(function (dt) {
1042
+ self(_action, dt);
1043
+ });
1044
+ });
1045
+ };
1046
+
1047
+ /**
1048
+ * Schedules an action to be executed recursively at a specified absolute due time.
1049
+ * @param {Mixed} state State passed to the action to be executed.
1050
+ * @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.
1051
+ * @param {Number}dueTime Absolute time at which to execute the action for the first time.
1052
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
1053
+ */
1054
+ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
1055
+ return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
1056
+ return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
1057
+ });
1058
+ };
1059
+
1060
+ /** Gets the current time according to the local machine's system clock. */
1061
+ Scheduler.now = defaultNow;
1062
+
1063
+ /**
1064
+ * Normalizes the specified TimeSpan value to a positive value.
1065
+ * @param {Number} timeSpan The time span value to normalize.
1066
+ * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
1067
+ */
1068
+ Scheduler.normalize = function (timeSpan) {
1069
+ if (timeSpan < 0) {
1070
+ timeSpan = 0;
1071
+ }
1072
+ return timeSpan;
1073
+ };
1074
+
1075
+ return Scheduler;
1076
+ }());
1077
+
1078
+ var normalizeTime = Scheduler.normalize;
1079
+
1080
+ var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () {
1081
+ function tick(command, recurse) {
1082
+ recurse(0, this._period);
1083
+ try {
1084
+ this._state = this._action(this._state);
1085
+ } catch (e) {
1086
+ this._cancel.dispose();
1087
+ throw e;
1088
+ }
1089
+ }
1090
+
1091
+ function SchedulePeriodicRecursive(scheduler, state, period, action) {
1092
+ this._scheduler = scheduler;
1093
+ this._state = state;
1094
+ this._period = period;
1095
+ this._action = action;
1096
+ }
1097
+
1098
+ SchedulePeriodicRecursive.prototype.start = function () {
1099
+ var d = new SingleAssignmentDisposable();
1100
+ this._cancel = d;
1101
+ d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
1102
+
1103
+ return d;
1104
+ };
1105
+
1106
+ return SchedulePeriodicRecursive;
1107
+ }());
1108
+
1109
+ /**
1110
+ * Gets a scheduler that schedules work immediately on the current thread.
1111
+ */
1112
+ var immediateScheduler = Scheduler.immediate = (function () {
1113
+
1114
+ function scheduleNow(state, action) { return action(this, state); }
1115
+
1116
+ function scheduleRelative(state, dueTime, action) {
1117
+ var dt = normalizeTime(dt);
1118
+ while (dt - this.now() > 0) { }
1119
+ return action(this, state);
1120
+ }
1121
+
1122
+ function scheduleAbsolute(state, dueTime, action) {
1123
+ return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
1124
+ }
1125
+
1126
+ return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
1127
+ }());
1128
+
1129
+ /**
1130
+ * Gets a scheduler that schedules work as soon as possible on the current thread.
1131
+ */
1132
+ var currentThreadScheduler = Scheduler.currentThread = (function () {
1133
+ var queue;
1134
+
1135
+ function Trampoline() {
1136
+ queue = new PriorityQueue(4);
1137
+ }
1138
+
1139
+ Trampoline.prototype.dispose = function () {
1140
+ queue = null;
1141
+ };
1142
+
1143
+ Trampoline.prototype.run = function () {
1144
+ var item;
1145
+ while (queue.length > 0) {
1146
+ item = queue.dequeue();
1147
+ if (!item.isCancelled()) {
1148
+ while (item.dueTime - Scheduler.now() > 0) { }
1149
+ if (!item.isCancelled()) {
1150
+ item.invoke();
1151
+ }
1152
+ }
1153
+ }
1154
+ };
1155
+
1156
+ function scheduleNow(state, action) {
1157
+ return this.scheduleWithRelativeAndState(state, 0, action);
1158
+ }
1159
+
1160
+ function scheduleRelative(state, dueTime, action) {
1161
+ var dt = this.now() + normalizeTime(dueTime),
1162
+ si = new ScheduledItem(this, state, action, dt),
1163
+ t;
1164
+ if (!queue) {
1165
+ t = new Trampoline();
1166
+ try {
1167
+ queue.enqueue(si);
1168
+ t.run();
1169
+ } catch (e) {
1170
+ throw e;
1171
+ } finally {
1172
+ t.dispose();
1173
+ }
1174
+ } else {
1175
+ queue.enqueue(si);
1176
+ }
1177
+ return si.disposable;
1178
+ }
1179
+
1180
+ function scheduleAbsolute(state, dueTime, action) {
1181
+ return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
1182
+ }
1183
+
1184
+ var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
1185
+ currentScheduler.scheduleRequired = function () { return queue === null; };
1186
+ currentScheduler.ensureTrampoline = function (action) {
1187
+ if (queue === null) {
1188
+ return this.schedule(action);
1189
+ } else {
1190
+ return action();
1191
+ }
1192
+ };
1193
+
1194
+ return currentScheduler;
1195
+ }());
1196
+
1197
+
1198
+ var reNative = RegExp('^' +
1199
+ String(toString)
1200
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1201
+ .replace(/toString| for [^\]]+/g, '.*?') + '$'
1202
+ );
1203
+
1204
+ var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
1205
+ !reNative.test(setImmediate) && setImmediate,
1206
+ clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
1207
+ !reNative.test(clearImmediate) && clearImmediate;
1208
+
1209
+ var scheduleMethod, clearMethod = noop;
1210
+ (function () {
1211
+ function postMessageSupported () {
1212
+ // Ensure not in a worker
1213
+ if (!root.postMessage || root.importScripts) { return false; }
1214
+ var isAsync = false,
1215
+ oldHandler = root.onmessage;
1216
+ // Test for async
1217
+ root.onmessage = function () { isAsync = true; };
1218
+ root.postMessage('','*');
1219
+ root.onmessage = oldHandler;
1220
+
1221
+ return isAsync;
1222
+ }
1223
+
1224
+ // Check for setImmediate first for Node v0.11+
1225
+ if (typeof setImmediate === 'function') {
1226
+ scheduleMethod = setImmediate;
1227
+ clearMethod = clearImmediate;
1228
+ } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
1229
+ scheduleMethod = process.nextTick;
1230
+ } else if (postMessageSupported()) {
1231
+ var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
1232
+ tasks = {},
1233
+ taskId = 0;
1234
+
1235
+ function onGlobalPostMessage(event) {
1236
+ // Only if we're a match to avoid any other global events
1237
+ if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
1238
+ var handleId = event.data.substring(MSG_PREFIX.length),
1239
+ action = tasks[handleId];
1240
+ action();
1241
+ delete tasks[handleId];
1242
+ }
1243
+ }
1244
+
1245
+ if (root.addEventListener) {
1246
+ root.addEventListener('message', onGlobalPostMessage, false);
1247
+ } else {
1248
+ root.attachEvent('onmessage', onGlobalPostMessage, false);
1249
+ }
1250
+
1251
+ scheduleMethod = function (action) {
1252
+ var currentId = taskId++;
1253
+ tasks[currentId] = action;
1254
+ root.postMessage(MSG_PREFIX + currentId, '*');
1255
+ };
1256
+ } else if (!!root.MessageChannel) {
1257
+ var channel = new root.MessageChannel(),
1258
+ channelTasks = {},
1259
+ channelTaskId = 0;
1260
+
1261
+ channel.port1.onmessage = function (event) {
1262
+ var id = event.data,
1263
+ action = channelTasks[id];
1264
+ action();
1265
+ delete channelTasks[id];
1266
+ };
1267
+
1268
+ scheduleMethod = function (action) {
1269
+ var id = channelTaskId++;
1270
+ channelTasks[id] = action;
1271
+ channel.port2.postMessage(id);
1272
+ };
1273
+ } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
1274
+
1275
+ scheduleMethod = function (action) {
1276
+ var scriptElement = root.document.createElement('script');
1277
+ scriptElement.onreadystatechange = function () {
1278
+ action();
1279
+ scriptElement.onreadystatechange = null;
1280
+ scriptElement.parentNode.removeChild(scriptElement);
1281
+ scriptElement = null;
1282
+ };
1283
+ root.document.documentElement.appendChild(scriptElement);
1284
+ };
1285
+
1286
+ } else {
1287
+ scheduleMethod = function (action) { return setTimeout(action, 0); };
1288
+ clearMethod = clearTimeout;
1289
+ }
1290
+ }());
1291
+
1292
+ /**
1293
+ * Gets a scheduler that schedules work via a timed callback based upon platform.
1294
+ */
1295
+ var timeoutScheduler = Scheduler.timeout = (function () {
1296
+
1297
+ function scheduleNow(state, action) {
1298
+ var scheduler = this,
1299
+ disposable = new SingleAssignmentDisposable();
1300
+ var id = scheduleMethod(function () {
1301
+ if (!disposable.isDisposed) {
1302
+ disposable.setDisposable(action(scheduler, state));
1303
+ }
1304
+ });
1305
+ return new CompositeDisposable(disposable, disposableCreate(function () {
1306
+ clearMethod(id);
1307
+ }));
1308
+ }
1309
+
1310
+ function scheduleRelative(state, dueTime, action) {
1311
+ var scheduler = this,
1312
+ dt = Scheduler.normalize(dueTime);
1313
+ if (dt === 0) {
1314
+ return scheduler.scheduleWithState(state, action);
1315
+ }
1316
+ var disposable = new SingleAssignmentDisposable();
1317
+ var id = setTimeout(function () {
1318
+ if (!disposable.isDisposed) {
1319
+ disposable.setDisposable(action(scheduler, state));
1320
+ }
1321
+ }, dt);
1322
+ return new CompositeDisposable(disposable, disposableCreate(function () {
1323
+ clearTimeout(id);
1324
+ }));
1325
+ }
1326
+
1327
+ function scheduleAbsolute(state, dueTime, action) {
1328
+ return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
1329
+ }
1330
+
1331
+ return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
1332
+ })();
1333
+
1334
+ /** @private */
1335
+ var CatchScheduler = (function (_super) {
1336
+
1337
+ function localNow() {
1338
+ return this._scheduler.now();
1339
+ }
1340
+
1341
+ function scheduleNow(state, action) {
1342
+ return this._scheduler.scheduleWithState(state, this._wrap(action));
1343
+ }
1344
+
1345
+ function scheduleRelative(state, dueTime, action) {
1346
+ return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
1347
+ }
1348
+
1349
+ function scheduleAbsolute(state, dueTime, action) {
1350
+ return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
1351
+ }
1352
+
1353
+ inherits(CatchScheduler, _super);
1354
+
1355
+ /** @private */
1356
+ function CatchScheduler(scheduler, handler) {
1357
+ this._scheduler = scheduler;
1358
+ this._handler = handler;
1359
+ this._recursiveOriginal = null;
1360
+ this._recursiveWrapper = null;
1361
+ _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
1362
+ }
1363
+
1364
+ /** @private */
1365
+ CatchScheduler.prototype._clone = function (scheduler) {
1366
+ return new CatchScheduler(scheduler, this._handler);
1367
+ };
1368
+
1369
+ /** @private */
1370
+ CatchScheduler.prototype._wrap = function (action) {
1371
+ var parent = this;
1372
+ return function (self, state) {
1373
+ try {
1374
+ return action(parent._getRecursiveWrapper(self), state);
1375
+ } catch (e) {
1376
+ if (!parent._handler(e)) { throw e; }
1377
+ return disposableEmpty;
1378
+ }
1379
+ };
1380
+ };
1381
+
1382
+ /** @private */
1383
+ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
1384
+ if (this._recursiveOriginal !== scheduler) {
1385
+ this._recursiveOriginal = scheduler;
1386
+ var wrapper = this._clone(scheduler);
1387
+ wrapper._recursiveOriginal = scheduler;
1388
+ wrapper._recursiveWrapper = wrapper;
1389
+ this._recursiveWrapper = wrapper;
1390
+ }
1391
+ return this._recursiveWrapper;
1392
+ };
1393
+
1394
+ /** @private */
1395
+ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
1396
+ var self = this, failed = false, d = new SingleAssignmentDisposable();
1397
+
1398
+ d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
1399
+ if (failed) { return null; }
1400
+ try {
1401
+ return action(state1);
1402
+ } catch (e) {
1403
+ failed = true;
1404
+ if (!self._handler(e)) { throw e; }
1405
+ d.dispose();
1406
+ return null;
1407
+ }
1408
+ }));
1409
+
1410
+ return d;
1411
+ };
1412
+
1413
+ return CatchScheduler;
1414
+ }(Scheduler));
1415
+
1416
+ /**
1417
+ * Represents a notification to an observer.
1418
+ */
1419
+ var Notification = Rx.Notification = (function () {
1420
+ function Notification(kind, hasValue) {
1421
+ this.hasValue = hasValue == null ? false : hasValue;
1422
+ this.kind = kind;
1423
+ }
1424
+
1425
+ var NotificationPrototype = Notification.prototype;
1426
+
1427
+ /**
1428
+ * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
1429
+ *
1430
+ * @memberOf Notification
1431
+ * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
1432
+ * @param {Function} onError Delegate to invoke for an OnError notification.
1433
+ * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
1434
+ * @returns {Any} Result produced by the observation.
1435
+ */
1436
+ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
1437
+ if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
1438
+ return this._acceptObservable(observerOrOnNext);
1439
+ }
1440
+ return this._accept(observerOrOnNext, onError, onCompleted);
1441
+ };
1442
+
1443
+ /**
1444
+ * Returns an observable sequence with a single notification.
1445
+ *
1446
+ * @memberOf Notification
1447
+ * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
1448
+ * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
1449
+ */
1450
+ NotificationPrototype.toObservable = function (scheduler) {
1451
+ var notification = this;
1452
+ scheduler || (scheduler = immediateScheduler);
1453
+ return new AnonymousObservable(function (observer) {
1454
+ return scheduler.schedule(function () {
1455
+ notification._acceptObservable(observer);
1456
+ if (notification.kind === 'N') {
1457
+ observer.onCompleted();
1458
+ }
1459
+ });
1460
+ });
1461
+ };
1462
+
1463
+ return Notification;
1464
+ })();
1465
+
1466
+ /**
1467
+ * Creates an object that represents an OnNext notification to an observer.
1468
+ * @param {Any} value The value contained in the notification.
1469
+ * @returns {Notification} The OnNext notification containing the value.
1470
+ */
1471
+ var notificationCreateOnNext = Notification.createOnNext = (function () {
1472
+
1473
+ function _accept (onNext) {
1474
+ return onNext(this.value);
1475
+ }
1476
+
1477
+ function _acceptObservable(observer) {
1478
+ return observer.onNext(this.value);
1479
+ }
1480
+
1481
+ function toString () {
1482
+ return 'OnNext(' + this.value + ')';
1483
+ }
1484
+
1485
+ return function (value) {
1486
+ var notification = new Notification('N', true);
1487
+ notification.value = value;
1488
+ notification._accept = _accept;
1489
+ notification._acceptObservable = _acceptObservable;
1490
+ notification.toString = toString;
1491
+ return notification;
1492
+ };
1493
+ }());
1494
+
1495
+ /**
1496
+ * Creates an object that represents an OnError notification to an observer.
1497
+ * @param {Any} error The exception contained in the notification.
1498
+ * @returns {Notification} The OnError notification containing the exception.
1499
+ */
1500
+ var notificationCreateOnError = Notification.createOnError = (function () {
1501
+
1502
+ function _accept (onNext, onError) {
1503
+ return onError(this.exception);
1504
+ }
1505
+
1506
+ function _acceptObservable(observer) {
1507
+ return observer.onError(this.exception);
1508
+ }
1509
+
1510
+ function toString () {
1511
+ return 'OnError(' + this.exception + ')';
1512
+ }
1513
+
1514
+ return function (exception) {
1515
+ var notification = new Notification('E');
1516
+ notification.exception = exception;
1517
+ notification._accept = _accept;
1518
+ notification._acceptObservable = _acceptObservable;
1519
+ notification.toString = toString;
1520
+ return notification;
1521
+ };
1522
+ }());
1523
+
1524
+ /**
1525
+ * Creates an object that represents an OnCompleted notification to an observer.
1526
+ * @returns {Notification} The OnCompleted notification.
1527
+ */
1528
+ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
1529
+
1530
+ function _accept (onNext, onError, onCompleted) {
1531
+ return onCompleted();
1532
+ }
1533
+
1534
+ function _acceptObservable(observer) {
1535
+ return observer.onCompleted();
1536
+ }
1537
+
1538
+ function toString () {
1539
+ return 'OnCompleted()';
1540
+ }
1541
+
1542
+ return function () {
1543
+ var notification = new Notification('C');
1544
+ notification._accept = _accept;
1545
+ notification._acceptObservable = _acceptObservable;
1546
+ notification.toString = toString;
1547
+ return notification;
1548
+ };
1549
+ }());
1550
+
1551
+ /**
1552
+ * @constructor
1553
+ * @private
1554
+ */
1555
+ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent) {
1556
+ this.moveNext = moveNext;
1557
+ this.getCurrent = getCurrent;
1558
+ };
1559
+
1560
+ /**
1561
+ * @static
1562
+ * @memberOf Enumerator
1563
+ * @private
1564
+ */
1565
+ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent) {
1566
+ var done = false;
1567
+ return new Enumerator(function () {
1568
+ if (done) {
1569
+ return false;
1570
+ }
1571
+ var result = moveNext();
1572
+ if (!result) {
1573
+ done = true;
1574
+ }
1575
+ return result;
1576
+ }, function () { return getCurrent(); });
1577
+ };
1578
+
1579
+ var Enumerable = Rx.Internals.Enumerable = function (getEnumerator) {
1580
+ this.getEnumerator = getEnumerator;
1581
+ };
1582
+
1583
+ Enumerable.prototype.concat = function () {
1584
+ var sources = this;
1585
+ return new AnonymousObservable(function (observer) {
1586
+ var e = sources.getEnumerator(), isDisposed, subscription = new SerialDisposable();
1587
+ var cancelable = immediateScheduler.scheduleRecursive(function (self) {
1588
+ var current, hasNext;
1589
+ if (isDisposed) { return; }
1590
+
1591
+ try {
1592
+ hasNext = e.moveNext();
1593
+ if (hasNext) {
1594
+ current = e.getCurrent();
1595
+ }
1596
+ } catch (ex) {
1597
+ observer.onError(ex);
1598
+ return;
1599
+ }
1600
+
1601
+ if (!hasNext) {
1602
+ observer.onCompleted();
1603
+ return;
1604
+ }
1605
+
1606
+ var d = new SingleAssignmentDisposable();
1607
+ subscription.setDisposable(d);
1608
+ d.setDisposable(current.subscribe(
1609
+ observer.onNext.bind(observer),
1610
+ observer.onError.bind(observer),
1611
+ function () { self(); })
1612
+ );
1613
+ });
1614
+ return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
1615
+ isDisposed = true;
1616
+ }));
1617
+ });
1618
+ };
1619
+
1620
+ Enumerable.prototype.catchException = function () {
1621
+ var sources = this;
1622
+ return new AnonymousObservable(function (observer) {
1623
+ var e = sources.getEnumerator(), isDisposed, lastException;
1624
+ var subscription = new SerialDisposable();
1625
+ var cancelable = immediateScheduler.scheduleRecursive(function (self) {
1626
+ var current, hasNext;
1627
+ if (isDisposed) { return; }
1628
+
1629
+ try {
1630
+ hasNext = e.moveNext();
1631
+ if (hasNext) {
1632
+ current = e.getCurrent();
1633
+ }
1634
+ } catch (ex) {
1635
+ observer.onError(ex);
1636
+ return;
1637
+ }
1638
+
1639
+ if (!hasNext) {
1640
+ if (lastException) {
1641
+ observer.onError(lastException);
1642
+ } else {
1643
+ observer.onCompleted();
1644
+ }
1645
+ return;
1646
+ }
1647
+
1648
+ var d = new SingleAssignmentDisposable();
1649
+ subscription.setDisposable(d);
1650
+ d.setDisposable(current.subscribe(
1651
+ observer.onNext.bind(observer),
1652
+ function (exn) {
1653
+ lastException = exn;
1654
+ self();
1655
+ },
1656
+ observer.onCompleted.bind(observer)));
1657
+ });
1658
+ return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
1659
+ isDisposed = true;
1660
+ }));
1661
+ });
1662
+ };
1663
+
1664
+
1665
+ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
1666
+ if (arguments.length === 1) {
1667
+ repeatCount = -1;
1668
+ }
1669
+ return new Enumerable(function () {
1670
+ var current, left = repeatCount;
1671
+ return enumeratorCreate(function () {
1672
+ if (left === 0) {
1673
+ return false;
1674
+ }
1675
+ if (left > 0) {
1676
+ left--;
1677
+ }
1678
+ current = value;
1679
+ return true;
1680
+ }, function () { return current; });
1681
+ });
1682
+ };
1683
+
1684
+ var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
1685
+ selector || (selector = identity);
1686
+ return new Enumerable(function () {
1687
+ var current, index = -1;
1688
+ return enumeratorCreate(
1689
+ function () {
1690
+ if (++index < source.length) {
1691
+ current = selector.call(thisArg, source[index], index, source);
1692
+ return true;
1693
+ }
1694
+ return false;
1695
+ },
1696
+ function () { return current; }
1697
+ );
1698
+ });
1699
+ };
1700
+
1701
+ /**
1702
+ * Supports push-style iteration over an observable sequence.
1703
+ */
1704
+ var Observer = Rx.Observer = function () { };
1705
+
1706
+ /**
1707
+ * Creates a notification callback from an observer.
1708
+ *
1709
+ * @param observer Observer object.
1710
+ * @returns The action that forwards its input notification to the underlying observer.
1711
+ */
1712
+ Observer.prototype.toNotifier = function () {
1713
+ var observer = this;
1714
+ return function (n) {
1715
+ return n.accept(observer);
1716
+ };
1717
+ };
1718
+
1719
+ /**
1720
+ * Hides the identity of an observer.
1721
+
1722
+ * @returns An observer that hides the identity of the specified observer.
1723
+ */
1724
+ Observer.prototype.asObserver = function () {
1725
+ return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
1726
+ };
1727
+
1728
+ /**
1729
+ * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
1730
+ * If a violation is detected, an Error is thrown from the offending observer method call.
1731
+ *
1732
+ * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
1733
+ */
1734
+ Observer.prototype.checked = function () { return new CheckedObserver(this); };
1735
+
1736
+ /**
1737
+ * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
1738
+ *
1739
+ * @static
1740
+ * @memberOf Observer
1741
+ * @param {Function} [onNext] Observer's OnNext action implementation.
1742
+ * @param {Function} [onError] Observer's OnError action implementation.
1743
+ * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
1744
+ * @returns {Observer} The observer object implemented using the given actions.
1745
+ */
1746
+ var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
1747
+ onNext || (onNext = noop);
1748
+ onError || (onError = defaultError);
1749
+ onCompleted || (onCompleted = noop);
1750
+ return new AnonymousObserver(onNext, onError, onCompleted);
1751
+ };
1752
+
1753
+ /**
1754
+ * Creates an observer from a notification callback.
1755
+ *
1756
+ * @static
1757
+ * @memberOf Observer
1758
+ * @param {Function} handler Action that handles a notification.
1759
+ * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
1760
+ */
1761
+ Observer.fromNotifier = function (handler) {
1762
+ return new AnonymousObserver(function (x) {
1763
+ return handler(notificationCreateOnNext(x));
1764
+ }, function (exception) {
1765
+ return handler(notificationCreateOnError(exception));
1766
+ }, function () {
1767
+ return handler(notificationCreateOnCompleted());
1768
+ });
1769
+ };
1770
+
1771
+ /**
1772
+ * Schedules the invocation of observer methods on the given scheduler.
1773
+ * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
1774
+ * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
1775
+ */
1776
+ Observer.notifyOn = function (scheduler) {
1777
+ return new ObserveOnObserver(scheduler, this);
1778
+ };
1779
+
1780
+ /**
1781
+ * Abstract base class for implementations of the Observer class.
1782
+ * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
1783
+ */
1784
+ var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) {
1785
+ inherits(AbstractObserver, _super);
1786
+
1787
+ /**
1788
+ * Creates a new observer in a non-stopped state.
1789
+ *
1790
+ * @constructor
1791
+ */
1792
+ function AbstractObserver() {
1793
+ this.isStopped = false;
1794
+ _super.call(this);
1795
+ }
1796
+
1797
+ /**
1798
+ * Notifies the observer of a new element in the sequence.
1799
+ *
1800
+ * @memberOf AbstractObserver
1801
+ * @param {Any} value Next element in the sequence.
1802
+ */
1803
+ AbstractObserver.prototype.onNext = function (value) {
1804
+ if (!this.isStopped) {
1805
+ this.next(value);
1806
+ }
1807
+ };
1808
+
1809
+ /**
1810
+ * Notifies the observer that an exception has occurred.
1811
+ *
1812
+ * @memberOf AbstractObserver
1813
+ * @param {Any} error The error that has occurred.
1814
+ */
1815
+ AbstractObserver.prototype.onError = function (error) {
1816
+ if (!this.isStopped) {
1817
+ this.isStopped = true;
1818
+ this.error(error);
1819
+ }
1820
+ };
1821
+
1822
+ /**
1823
+ * Notifies the observer of the end of the sequence.
1824
+ */
1825
+ AbstractObserver.prototype.onCompleted = function () {
1826
+ if (!this.isStopped) {
1827
+ this.isStopped = true;
1828
+ this.completed();
1829
+ }
1830
+ };
1831
+
1832
+ /**
1833
+ * Disposes the observer, causing it to transition to the stopped state.
1834
+ */
1835
+ AbstractObserver.prototype.dispose = function () {
1836
+ this.isStopped = true;
1837
+ };
1838
+
1839
+ AbstractObserver.prototype.fail = function (e) {
1840
+ if (!this.isStopped) {
1841
+ this.isStopped = true;
1842
+ this.error(e);
1843
+ return true;
1844
+ }
1845
+
1846
+ return false;
1847
+ };
1848
+
1849
+ return AbstractObserver;
1850
+ }(Observer));
1851
+
1852
+ /**
1853
+ * Class to create an Observer instance from delegate-based implementations of the on* methods.
1854
+ */
1855
+ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
1856
+ inherits(AnonymousObserver, _super);
1857
+
1858
+ /**
1859
+ * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
1860
+ *
1861
+ * @constructor
1862
+ * @param {Any} onNext Observer's OnNext action implementation.
1863
+ * @param {Any} onError Observer's OnError action implementation.
1864
+ * @param {Any} onCompleted Observer's OnCompleted action implementation.
1865
+ */
1866
+ function AnonymousObserver(onNext, onError, onCompleted) {
1867
+ _super.call(this);
1868
+ this._onNext = onNext;
1869
+ this._onError = onError;
1870
+ this._onCompleted = onCompleted;
1871
+ }
1872
+
1873
+ /**
1874
+ * Calls the onNext action.
1875
+ *
1876
+ * @memberOf AnonymousObserver
1877
+ * @param {Any} value Next element in the sequence.
1878
+ */
1879
+ AnonymousObserver.prototype.next = function (value) {
1880
+ this._onNext(value);
1881
+ };
1882
+
1883
+ /**
1884
+ * Calls the onError action.
1885
+ *
1886
+ * @memberOf AnonymousObserver
1887
+ * @param {Any{ error The error that has occurred.
1888
+ */
1889
+ AnonymousObserver.prototype.error = function (exception) {
1890
+ this._onError(exception);
1891
+ };
1892
+
1893
+ /**
1894
+ * Calls the onCompleted action.
1895
+ *
1896
+ * @memberOf AnonymousObserver
1897
+ */
1898
+ AnonymousObserver.prototype.completed = function () {
1899
+ this._onCompleted();
1900
+ };
1901
+
1902
+ return AnonymousObserver;
1903
+ }(AbstractObserver));
1904
+
1905
+ var CheckedObserver = (function (_super) {
1906
+ inherits(CheckedObserver, _super);
1907
+
1908
+ function CheckedObserver(observer) {
1909
+ _super.call(this);
1910
+ this._observer = observer;
1911
+ this._state = 0; // 0 - idle, 1 - busy, 2 - done
1912
+ }
1913
+
1914
+ var CheckedObserverPrototype = CheckedObserver.prototype;
1915
+
1916
+ CheckedObserverPrototype.onNext = function (value) {
1917
+ this.checkAccess();
1918
+ try {
1919
+ this._observer.onNext(value);
1920
+ } catch (e) {
1921
+ throw e;
1922
+ } finally {
1923
+ this._state = 0;
1924
+ }
1925
+ };
1926
+
1927
+ CheckedObserverPrototype.onError = function (err) {
1928
+ this.checkAccess();
1929
+ try {
1930
+ this._observer.onError(err);
1931
+ } catch (e) {
1932
+ throw e;
1933
+ } finally {
1934
+ this._state = 2;
1935
+ }
1936
+ };
1937
+
1938
+ CheckedObserverPrototype.onCompleted = function () {
1939
+ this.checkAccess();
1940
+ try {
1941
+ this._observer.onCompleted();
1942
+ } catch (e) {
1943
+ throw e;
1944
+ } finally {
1945
+ this._state = 2;
1946
+ }
1947
+ };
1948
+
1949
+ CheckedObserverPrototype.checkAccess = function () {
1950
+ if (this._state === 1) { throw new Error('Re-entrancy detected'); }
1951
+ if (this._state === 2) { throw new Error('Observer completed'); }
1952
+ if (this._state === 0) { this._state = 1; }
1953
+ };
1954
+
1955
+ return CheckedObserver;
1956
+ }(Observer));
1957
+
1958
+ /** @private */
1959
+ var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
1960
+ inherits(ScheduledObserver, _super);
1961
+
1962
+ function ScheduledObserver(scheduler, observer) {
1963
+ _super.call(this);
1964
+ this.scheduler = scheduler;
1965
+ this.observer = observer;
1966
+ this.isAcquired = false;
1967
+ this.hasFaulted = false;
1968
+ this.queue = [];
1969
+ this.disposable = new SerialDisposable();
1970
+ }
1971
+
1972
+ /** @private */
1973
+ ScheduledObserver.prototype.next = function (value) {
1974
+ var self = this;
1975
+ this.queue.push(function () {
1976
+ self.observer.onNext(value);
1977
+ });
1978
+ };
1979
+
1980
+ /** @private */
1981
+ ScheduledObserver.prototype.error = function (exception) {
1982
+ var self = this;
1983
+ this.queue.push(function () {
1984
+ self.observer.onError(exception);
1985
+ });
1986
+ };
1987
+
1988
+ /** @private */
1989
+ ScheduledObserver.prototype.completed = function () {
1990
+ var self = this;
1991
+ this.queue.push(function () {
1992
+ self.observer.onCompleted();
1993
+ });
1994
+ };
1995
+
1996
+ /** @private */
1997
+ ScheduledObserver.prototype.ensureActive = function () {
1998
+ var isOwner = false, parent = this;
1999
+ if (!this.hasFaulted && this.queue.length > 0) {
2000
+ isOwner = !this.isAcquired;
2001
+ this.isAcquired = true;
2002
+ }
2003
+ if (isOwner) {
2004
+ this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
2005
+ var work;
2006
+ if (parent.queue.length > 0) {
2007
+ work = parent.queue.shift();
2008
+ } else {
2009
+ parent.isAcquired = false;
2010
+ return;
2011
+ }
2012
+ try {
2013
+ work();
2014
+ } catch (ex) {
2015
+ parent.queue = [];
2016
+ parent.hasFaulted = true;
2017
+ throw ex;
2018
+ }
2019
+ self();
2020
+ }));
2021
+ }
2022
+ };
2023
+
2024
+ /** @private */
2025
+ ScheduledObserver.prototype.dispose = function () {
2026
+ _super.prototype.dispose.call(this);
2027
+ this.disposable.dispose();
2028
+ };
2029
+
2030
+ return ScheduledObserver;
2031
+ }(AbstractObserver));
2032
+
2033
+ /** @private */
2034
+ var ObserveOnObserver = (function (_super) {
2035
+ inherits(ObserveOnObserver, _super);
2036
+
2037
+ /** @private */
2038
+ function ObserveOnObserver() {
2039
+ _super.apply(this, arguments);
2040
+ }
2041
+
2042
+ /** @private */
2043
+ ObserveOnObserver.prototype.next = function (value) {
2044
+ _super.prototype.next.call(this, value);
2045
+ this.ensureActive();
2046
+ };
2047
+
2048
+ /** @private */
2049
+ ObserveOnObserver.prototype.error = function (e) {
2050
+ _super.prototype.error.call(this, e);
2051
+ this.ensureActive();
2052
+ };
2053
+
2054
+ /** @private */
2055
+ ObserveOnObserver.prototype.completed = function () {
2056
+ _super.prototype.completed.call(this);
2057
+ this.ensureActive();
2058
+ };
2059
+
2060
+ return ObserveOnObserver;
2061
+ })(ScheduledObserver);
2062
+
2063
+ var observableProto;
2064
+
2065
+ /**
2066
+ * Represents a push-style collection.
2067
+ */
2068
+ var Observable = Rx.Observable = (function () {
2069
+
2070
+ /**
2071
+ * @constructor
2072
+ * @private
2073
+ */
2074
+ function Observable(subscribe) {
2075
+ this._subscribe = subscribe;
2076
+ }
2077
+
2078
+ observableProto = Observable.prototype;
2079
+
2080
+ observableProto.finalValue = function () {
2081
+ var source = this;
2082
+ return new AnonymousObservable(function (observer) {
2083
+ var hasValue = false, value;
2084
+ return source.subscribe(function (x) {
2085
+ hasValue = true;
2086
+ value = x;
2087
+ }, observer.onError.bind(observer), function () {
2088
+ if (!hasValue) {
2089
+ observer.onError(new Error(sequenceContainsNoElements));
2090
+ } else {
2091
+ observer.onNext(value);
2092
+ observer.onCompleted();
2093
+ }
2094
+ });
2095
+ });
2096
+ };
2097
+
2098
+ /**
2099
+ * Subscribes an observer to the observable sequence.
2100
+ *
2101
+ * @example
2102
+ * 1 - source.subscribe();
2103
+ * 2 - source.subscribe(observer);
2104
+ * 3 - source.subscribe(function (x) { console.log(x); });
2105
+ * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
2106
+ * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
2107
+ * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
2108
+ * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
2109
+ * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
2110
+ * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
2111
+ */
2112
+ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
2113
+ var subscriber;
2114
+ if (typeof observerOrOnNext === 'object') {
2115
+ subscriber = observerOrOnNext;
2116
+ } else {
2117
+ subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
2118
+ }
2119
+
2120
+ return this._subscribe(subscriber);
2121
+ };
2122
+
2123
+ /**
2124
+ * Creates a list from an observable sequence.
2125
+ *
2126
+ * @memberOf Observable
2127
+ * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
2128
+ */
2129
+ observableProto.toArray = function () {
2130
+ function accumulator(list, i) {
2131
+ var newList = list.slice(0);
2132
+ newList.push(i);
2133
+ return newList;
2134
+ }
2135
+ return this.scan([], accumulator).startWith([]).finalValue();
2136
+ };
2137
+
2138
+ return Observable;
2139
+ })();
2140
+
2141
+ /**
2142
+ * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
2143
+ *
2144
+ * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
2145
+ * that require to be run on a scheduler, use subscribeOn.
2146
+ *
2147
+ * @param {Scheduler} scheduler Scheduler to notify observers on.
2148
+ * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
2149
+ */
2150
+ observableProto.observeOn = function (scheduler) {
2151
+ var source = this;
2152
+ return new AnonymousObservable(function (observer) {
2153
+ return source.subscribe(new ObserveOnObserver(scheduler, observer));
2154
+ });
2155
+ };
2156
+
2157
+ /**
2158
+ * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
2159
+ * see the remarks section for more information on the distinction between subscribeOn and observeOn.
2160
+
2161
+ * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
2162
+ * callbacks on a scheduler, use observeOn.
2163
+
2164
+ * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
2165
+ * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
2166
+ */
2167
+ observableProto.subscribeOn = function (scheduler) {
2168
+ var source = this;
2169
+ return new AnonymousObservable(function (observer) {
2170
+ var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
2171
+ d.setDisposable(m);
2172
+ m.setDisposable(scheduler.schedule(function () {
2173
+ d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
2174
+ }));
2175
+ return d;
2176
+ });
2177
+ };
2178
+
2179
+ /**
2180
+ * Creates an observable sequence from a specified subscribe method implementation.
2181
+ *
2182
+ * @example
2183
+ * var res = Rx.Observable.create(function (observer) { return function () { } );
2184
+ * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
2185
+ * var res = Rx.Observable.create(function (observer) { } );
2186
+ *
2187
+ * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
2188
+ * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
2189
+ */
2190
+ Observable.create = Observable.createWithDisposable = function (subscribe) {
2191
+ return new AnonymousObservable(subscribe);
2192
+ };
2193
+
2194
+ /**
2195
+ * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
2196
+ *
2197
+ * @example
2198
+ * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
2199
+ * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
2200
+ * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
2201
+ */
2202
+ var observableDefer = Observable.defer = function (observableFactory) {
2203
+ return new AnonymousObservable(function (observer) {
2204
+ var result;
2205
+ try {
2206
+ result = observableFactory();
2207
+ } catch (e) {
2208
+ return observableThrow(e).subscribe(observer);
2209
+ }
2210
+ return result.subscribe(observer);
2211
+ });
2212
+ };
2213
+
2214
+ /**
2215
+ * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
2216
+ *
2217
+ * @example
2218
+ * var res = Rx.Observable.empty();
2219
+ * var res = Rx.Observable.empty(Rx.Scheduler.timeout);
2220
+ * @param {Scheduler} [scheduler] Scheduler to send the termination call on.
2221
+ * @returns {Observable} An observable sequence with no elements.
2222
+ */
2223
+ var observableEmpty = Observable.empty = function (scheduler) {
2224
+ scheduler || (scheduler = immediateScheduler);
2225
+ return new AnonymousObservable(function (observer) {
2226
+ return scheduler.schedule(function () {
2227
+ observer.onCompleted();
2228
+ });
2229
+ });
2230
+ };
2231
+
2232
+ /**
2233
+ * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
2234
+ *
2235
+ * @example
2236
+ * var res = Rx.Observable.fromArray([1,2,3]);
2237
+ * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
2238
+ * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
2239
+ * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
2240
+ */
2241
+ var observableFromArray = Observable.fromArray = function (array, scheduler) {
2242
+ scheduler || (scheduler = currentThreadScheduler);
2243
+ return new AnonymousObservable(function (observer) {
2244
+ var count = 0;
2245
+ return scheduler.scheduleRecursive(function (self) {
2246
+ if (count < array.length) {
2247
+ observer.onNext(array[count++]);
2248
+ self();
2249
+ } else {
2250
+ observer.onCompleted();
2251
+ }
2252
+ });
2253
+ });
2254
+ };
2255
+
2256
+ /**
2257
+ * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
2258
+ *
2259
+ * @example
2260
+ * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
2261
+ * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
2262
+ * @param {Mixed} initialState Initial state.
2263
+ * @param {Function} condition Condition to terminate generation (upon returning false).
2264
+ * @param {Function} iterate Iteration step function.
2265
+ * @param {Function} resultSelector Selector function for results produced in the sequence.
2266
+ * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
2267
+ * @returns {Observable} The generated sequence.
2268
+ */
2269
+ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
2270
+ scheduler || (scheduler = currentThreadScheduler);
2271
+ return new AnonymousObservable(function (observer) {
2272
+ var first = true, state = initialState;
2273
+ return scheduler.scheduleRecursive(function (self) {
2274
+ var hasResult, result;
2275
+ try {
2276
+ if (first) {
2277
+ first = false;
2278
+ } else {
2279
+ state = iterate(state);
2280
+ }
2281
+ hasResult = condition(state);
2282
+ if (hasResult) {
2283
+ result = resultSelector(state);
2284
+ }
2285
+ } catch (exception) {
2286
+ observer.onError(exception);
2287
+ return;
2288
+ }
2289
+ if (hasResult) {
2290
+ observer.onNext(result);
2291
+ self();
2292
+ } else {
2293
+ observer.onCompleted();
2294
+ }
2295
+ });
2296
+ });
2297
+ };
2298
+
2299
+ /**
2300
+ * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
2301
+ * @returns {Observable} An observable sequence whose observers will never get called.
2302
+ */
2303
+ var observableNever = Observable.never = function () {
2304
+ return new AnonymousObservable(function () {
2305
+ return disposableEmpty;
2306
+ });
2307
+ };
2308
+
2309
+ /**
2310
+ * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
2311
+ *
2312
+ * @example
2313
+ * var res = Rx.Observable.range(0, 10);
2314
+ * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
2315
+ * @param {Number} start The value of the first integer in the sequence.
2316
+ * @param {Number} count The number of sequential integers to generate.
2317
+ * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
2318
+ * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
2319
+ */
2320
+ Observable.range = function (start, count, scheduler) {
2321
+ scheduler || (scheduler = currentThreadScheduler);
2322
+ return new AnonymousObservable(function (observer) {
2323
+ return scheduler.scheduleRecursiveWithState(0, function (i, self) {
2324
+ if (i < count) {
2325
+ observer.onNext(start + i);
2326
+ self(i + 1);
2327
+ } else {
2328
+ observer.onCompleted();
2329
+ }
2330
+ });
2331
+ });
2332
+ };
2333
+
2334
+ /**
2335
+ * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
2336
+ *
2337
+ * @example
2338
+ * var res = Rx.Observable.repeat(42);
2339
+ * var res = Rx.Observable.repeat(42, 4);
2340
+ * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
2341
+ * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
2342
+ * @param {Mixed} value Element to repeat.
2343
+ * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
2344
+ * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
2345
+ * @returns {Observable} An observable sequence that repeats the given element the specified number of times.
2346
+ */
2347
+ Observable.repeat = function (value, repeatCount, scheduler) {
2348
+ scheduler || (scheduler = currentThreadScheduler);
2349
+ if (repeatCount == null) {
2350
+ repeatCount = -1;
2351
+ }
2352
+ return observableReturn(value, scheduler).repeat(repeatCount);
2353
+ };
2354
+
2355
+ /**
2356
+ * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
2357
+ * There is an alias called 'returnValue' for browsers <IE9.
2358
+ *
2359
+ * @example
2360
+ * var res = Rx.Observable.return(42);
2361
+ * var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
2362
+ * @param {Mixed} value Single element in the resulting observable sequence.
2363
+ * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
2364
+ * @returns {Observable} An observable sequence containing the single specified element.
2365
+ */
2366
+ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
2367
+ scheduler || (scheduler = immediateScheduler);
2368
+ return new AnonymousObservable(function (observer) {
2369
+ return scheduler.schedule(function () {
2370
+ observer.onNext(value);
2371
+ observer.onCompleted();
2372
+ });
2373
+ });
2374
+ };
2375
+
2376
+ /**
2377
+ * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
2378
+ * There is an alias to this method called 'throwException' for browsers <IE9.
2379
+ *
2380
+ * @example
2381
+ * var res = Rx.Observable.throwException(new Error('Error'));
2382
+ * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
2383
+ * @param {Mixed} exception An object used for the sequence's termination.
2384
+ * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
2385
+ * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
2386
+ */
2387
+ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
2388
+ scheduler || (scheduler = immediateScheduler);
2389
+ return new AnonymousObservable(function (observer) {
2390
+ return scheduler.schedule(function () {
2391
+ observer.onError(exception);
2392
+ });
2393
+ });
2394
+ };
2395
+
2396
+ /**
2397
+ * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
2398
+ *
2399
+ * @example
2400
+ * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
2401
+ * @param {Function} resourceFactory Factory function to obtain a resource object.
2402
+ * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
2403
+ * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
2404
+ */
2405
+ Observable.using = function (resourceFactory, observableFactory) {
2406
+ return new AnonymousObservable(function (observer) {
2407
+ var disposable = disposableEmpty, resource, source;
2408
+ try {
2409
+ resource = resourceFactory();
2410
+ if (resource) {
2411
+ disposable = resource;
2412
+ }
2413
+ source = observableFactory(resource);
2414
+ } catch (exception) {
2415
+ return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
2416
+ }
2417
+ return new CompositeDisposable(source.subscribe(observer), disposable);
2418
+ });
2419
+ };
2420
+
2421
+ /**
2422
+ * Propagates the observable sequence that reacts first.
2423
+ * @param {Observable} rightSource Second observable sequence.
2424
+ * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
2425
+ */
2426
+ observableProto.amb = function (rightSource) {
2427
+ var leftSource = this;
2428
+ return new AnonymousObservable(function (observer) {
2429
+
2430
+ var choice,
2431
+ leftChoice = 'L', rightChoice = 'R',
2432
+ leftSubscription = new SingleAssignmentDisposable(),
2433
+ rightSubscription = new SingleAssignmentDisposable();
2434
+
2435
+ function choiceL() {
2436
+ if (!choice) {
2437
+ choice = leftChoice;
2438
+ rightSubscription.dispose();
2439
+ }
2440
+ }
2441
+
2442
+ function choiceR() {
2443
+ if (!choice) {
2444
+ choice = rightChoice;
2445
+ leftSubscription.dispose();
2446
+ }
2447
+ }
2448
+
2449
+ leftSubscription.setDisposable(leftSource.subscribe(function (left) {
2450
+ choiceL();
2451
+ if (choice === leftChoice) {
2452
+ observer.onNext(left);
2453
+ }
2454
+ }, function (err) {
2455
+ choiceL();
2456
+ if (choice === leftChoice) {
2457
+ observer.onError(err);
2458
+ }
2459
+ }, function () {
2460
+ choiceL();
2461
+ if (choice === leftChoice) {
2462
+ observer.onCompleted();
2463
+ }
2464
+ }));
2465
+
2466
+ rightSubscription.setDisposable(rightSource.subscribe(function (right) {
2467
+ choiceR();
2468
+ if (choice === rightChoice) {
2469
+ observer.onNext(right);
2470
+ }
2471
+ }, function (err) {
2472
+ choiceR();
2473
+ if (choice === rightChoice) {
2474
+ observer.onError(err);
2475
+ }
2476
+ }, function () {
2477
+ choiceR();
2478
+ if (choice === rightChoice) {
2479
+ observer.onCompleted();
2480
+ }
2481
+ }));
2482
+
2483
+ return new CompositeDisposable(leftSubscription, rightSubscription);
2484
+ });
2485
+ };
2486
+
2487
+ /**
2488
+ * Propagates the observable sequence that reacts first.
2489
+ *
2490
+ * @example
2491
+ * var = Rx.Observable.amb(xs, ys, zs);
2492
+ * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
2493
+ */
2494
+ Observable.amb = function () {
2495
+ var acc = observableNever(),
2496
+ items = argsOrArray(arguments, 0);
2497
+ function func(previous, current) {
2498
+ return previous.amb(current);
2499
+ }
2500
+ for (var i = 0, len = items.length; i < len; i++) {
2501
+ acc = func(acc, items[i]);
2502
+ }
2503
+ return acc;
2504
+ };
2505
+
2506
+ function observableCatchHandler(source, handler) {
2507
+ return new AnonymousObservable(function (observer) {
2508
+ var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
2509
+ subscription.setDisposable(d1);
2510
+ d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
2511
+ var d, result;
2512
+ try {
2513
+ result = handler(exception);
2514
+ } catch (ex) {
2515
+ observer.onError(ex);
2516
+ return;
2517
+ }
2518
+ d = new SingleAssignmentDisposable();
2519
+ subscription.setDisposable(d);
2520
+ d.setDisposable(result.subscribe(observer));
2521
+ }, observer.onCompleted.bind(observer)));
2522
+ return subscription;
2523
+ });
2524
+ }
2525
+
2526
+ /**
2527
+ * Continues an observable sequence that is terminated by an exception with the next observable sequence.
2528
+ * @example
2529
+ * 1 - xs.catchException(ys)
2530
+ * 2 - xs.catchException(function (ex) { return ys(ex); })
2531
+ * @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.
2532
+ * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
2533
+ */
2534
+ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
2535
+ if (typeof handlerOrSecond === 'function') {
2536
+ return observableCatchHandler(this, handlerOrSecond);
2537
+ }
2538
+ return observableCatch([this, handlerOrSecond]);
2539
+ };
2540
+
2541
+ /**
2542
+ * Continues an observable sequence that is terminated by an exception with the next observable sequence.
2543
+ *
2544
+ * @example
2545
+ * 1 - res = Rx.Observable.catchException(xs, ys, zs);
2546
+ * 2 - res = Rx.Observable.catchException([xs, ys, zs]);
2547
+ * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
2548
+ */
2549
+ var observableCatch = Observable.catchException = Observable['catch'] = function () {
2550
+ var items = argsOrArray(arguments, 0);
2551
+ return enumerableFor(items).catchException();
2552
+ };
2553
+
2554
+ /**
2555
+ * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
2556
+ * This can be in the form of an argument list of observables or an array.
2557
+ *
2558
+ * @example
2559
+ * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
2560
+ * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
2561
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
2562
+ */
2563
+ observableProto.combineLatest = function () {
2564
+ var args = slice.call(arguments);
2565
+ if (Array.isArray(args[0])) {
2566
+ args[0].unshift(this);
2567
+ } else {
2568
+ args.unshift(this);
2569
+ }
2570
+ return combineLatest.apply(this, args);
2571
+ };
2572
+
2573
+ /**
2574
+ * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
2575
+ *
2576
+ * @example
2577
+ * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
2578
+ * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
2579
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
2580
+ */
2581
+ var combineLatest = Observable.combineLatest = function () {
2582
+ var args = slice.call(arguments), resultSelector = args.pop();
2583
+
2584
+ if (Array.isArray(args[0])) {
2585
+ args = args[0];
2586
+ }
2587
+
2588
+ return new AnonymousObservable(function (observer) {
2589
+ var falseFactory = function () { return false; },
2590
+ n = args.length,
2591
+ hasValue = arrayInitialize(n, falseFactory),
2592
+ hasValueAll = false,
2593
+ isDone = arrayInitialize(n, falseFactory),
2594
+ values = new Array(n);
2595
+
2596
+ function next(i) {
2597
+ var res;
2598
+ hasValue[i] = true;
2599
+ if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
2600
+ try {
2601
+ res = resultSelector.apply(null, values);
2602
+ } catch (ex) {
2603
+ observer.onError(ex);
2604
+ return;
2605
+ }
2606
+ observer.onNext(res);
2607
+ } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
2608
+ observer.onCompleted();
2609
+ }
2610
+ }
2611
+
2612
+ function done (i) {
2613
+ isDone[i] = true;
2614
+ if (isDone.every(identity)) {
2615
+ observer.onCompleted();
2616
+ }
2617
+ }
2618
+
2619
+ var subscriptions = new Array(n);
2620
+ for (var idx = 0; idx < n; idx++) {
2621
+ (function (i) {
2622
+ subscriptions[i] = new SingleAssignmentDisposable();
2623
+ subscriptions[i].setDisposable(args[i].subscribe(function (x) {
2624
+ values[i] = x;
2625
+ next(i);
2626
+ }, observer.onError.bind(observer), function () {
2627
+ done(i);
2628
+ }));
2629
+ }(idx));
2630
+ }
2631
+
2632
+ return new CompositeDisposable(subscriptions);
2633
+ });
2634
+ };
2635
+
2636
+ /**
2637
+ * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
2638
+ *
2639
+ * @example
2640
+ * 1 - concatenated = xs.concat(ys, zs);
2641
+ * 2 - concatenated = xs.concat([ys, zs]);
2642
+ * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
2643
+ */
2644
+ observableProto.concat = function () {
2645
+ var items = slice.call(arguments, 0);
2646
+ items.unshift(this);
2647
+ return observableConcat.apply(this, items);
2648
+ };
2649
+
2650
+ /**
2651
+ * Concatenates all the observable sequences.
2652
+ *
2653
+ * @example
2654
+ * 1 - res = Rx.Observable.concat(xs, ys, zs);
2655
+ * 2 - res = Rx.Observable.concat([xs, ys, zs]);
2656
+ * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
2657
+ */
2658
+ var observableConcat = Observable.concat = function () {
2659
+ var sources = argsOrArray(arguments, 0);
2660
+ return enumerableFor(sources).concat();
2661
+ };
2662
+
2663
+ /**
2664
+ * Concatenates an observable sequence of observable sequences.
2665
+ * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
2666
+ */
2667
+ observableProto.concatObservable = observableProto.concatAll =function () {
2668
+ return this.merge(1);
2669
+ };
2670
+
2671
+ /**
2672
+ * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
2673
+ * Or merges two observable sequences into a single observable sequence.
2674
+ *
2675
+ * @example
2676
+ * 1 - merged = sources.merge(1);
2677
+ * 2 - merged = source.merge(otherSource);
2678
+ * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
2679
+ * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
2680
+ */
2681
+ observableProto.merge = function (maxConcurrentOrOther) {
2682
+ if (typeof maxConcurrentOrOther !== 'number') {
2683
+ return observableMerge(this, maxConcurrentOrOther);
2684
+ }
2685
+ var sources = this;
2686
+ return new AnonymousObservable(function (observer) {
2687
+ var activeCount = 0,
2688
+ group = new CompositeDisposable(),
2689
+ isStopped = false,
2690
+ q = [],
2691
+ subscribe = function (xs) {
2692
+ var subscription = new SingleAssignmentDisposable();
2693
+ group.add(subscription);
2694
+ subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
2695
+ var s;
2696
+ group.remove(subscription);
2697
+ if (q.length > 0) {
2698
+ s = q.shift();
2699
+ subscribe(s);
2700
+ } else {
2701
+ activeCount--;
2702
+ if (isStopped && activeCount === 0) {
2703
+ observer.onCompleted();
2704
+ }
2705
+ }
2706
+ }));
2707
+ };
2708
+ group.add(sources.subscribe(function (innerSource) {
2709
+ if (activeCount < maxConcurrentOrOther) {
2710
+ activeCount++;
2711
+ subscribe(innerSource);
2712
+ } else {
2713
+ q.push(innerSource);
2714
+ }
2715
+ }, observer.onError.bind(observer), function () {
2716
+ isStopped = true;
2717
+ if (activeCount === 0) {
2718
+ observer.onCompleted();
2719
+ }
2720
+ }));
2721
+ return group;
2722
+ });
2723
+ };
2724
+
2725
+ /**
2726
+ * Merges all the observable sequences into a single observable sequence.
2727
+ * The scheduler is optional and if not specified, the immediate scheduler is used.
2728
+ *
2729
+ * @example
2730
+ * 1 - merged = Rx.Observable.merge(xs, ys, zs);
2731
+ * 2 - merged = Rx.Observable.merge([xs, ys, zs]);
2732
+ * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
2733
+ * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
2734
+ * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
2735
+ */
2736
+ var observableMerge = Observable.merge = function () {
2737
+ var scheduler, sources;
2738
+ if (!arguments[0]) {
2739
+ scheduler = immediateScheduler;
2740
+ sources = slice.call(arguments, 1);
2741
+ } else if (arguments[0].now) {
2742
+ scheduler = arguments[0];
2743
+ sources = slice.call(arguments, 1);
2744
+ } else {
2745
+ scheduler = immediateScheduler;
2746
+ sources = slice.call(arguments, 0);
2747
+ }
2748
+ if (Array.isArray(sources[0])) {
2749
+ sources = sources[0];
2750
+ }
2751
+ return observableFromArray(sources, scheduler).mergeObservable();
2752
+ };
2753
+
2754
+ /**
2755
+ * Merges an observable sequence of observable sequences into an observable sequence.
2756
+ * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
2757
+ */
2758
+ observableProto.mergeObservable = observableProto.mergeAll =function () {
2759
+ var sources = this;
2760
+ return new AnonymousObservable(function (observer) {
2761
+ var group = new CompositeDisposable(),
2762
+ isStopped = false,
2763
+ m = new SingleAssignmentDisposable();
2764
+ group.add(m);
2765
+ m.setDisposable(sources.subscribe(function (innerSource) {
2766
+ var innerSubscription = new SingleAssignmentDisposable();
2767
+ group.add(innerSubscription);
2768
+ innerSubscription.setDisposable(innerSource.subscribe(function (x) {
2769
+ observer.onNext(x);
2770
+ }, observer.onError.bind(observer), function () {
2771
+ group.remove(innerSubscription);
2772
+ if (isStopped && group.length === 1) {
2773
+ observer.onCompleted();
2774
+ }
2775
+ }));
2776
+ }, observer.onError.bind(observer), function () {
2777
+ isStopped = true;
2778
+ if (group.length === 1) {
2779
+ observer.onCompleted();
2780
+ }
2781
+ }));
2782
+ return group;
2783
+ });
2784
+ };
2785
+
2786
+ /**
2787
+ * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
2788
+ * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
2789
+ * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
2790
+ */
2791
+ observableProto.onErrorResumeNext = function (second) {
2792
+ if (!second) {
2793
+ throw new Error('Second observable is required');
2794
+ }
2795
+ return onErrorResumeNext([this, second]);
2796
+ };
2797
+
2798
+ /**
2799
+ * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
2800
+ *
2801
+ * @example
2802
+ * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
2803
+ * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
2804
+ * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
2805
+ */
2806
+ var onErrorResumeNext = Observable.onErrorResumeNext = function () {
2807
+ var sources = argsOrArray(arguments, 0);
2808
+ return new AnonymousObservable(function (observer) {
2809
+ var pos = 0, subscription = new SerialDisposable(),
2810
+ cancelable = immediateScheduler.scheduleRecursive(function (self) {
2811
+ var current, d;
2812
+ if (pos < sources.length) {
2813
+ current = sources[pos++];
2814
+ d = new SingleAssignmentDisposable();
2815
+ subscription.setDisposable(d);
2816
+ d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
2817
+ self();
2818
+ }, function () {
2819
+ self();
2820
+ }));
2821
+ } else {
2822
+ observer.onCompleted();
2823
+ }
2824
+ });
2825
+ return new CompositeDisposable(subscription, cancelable);
2826
+ });
2827
+ };
2828
+
2829
+ /**
2830
+ * Returns the values from the source observable sequence only after the other observable sequence produces a value.
2831
+ * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence.
2832
+ * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
2833
+ */
2834
+ observableProto.skipUntil = function (other) {
2835
+ var source = this;
2836
+ return new AnonymousObservable(function (observer) {
2837
+ var isOpen = false;
2838
+ var disposables = new CompositeDisposable(source.subscribe(function (left) {
2839
+ if (isOpen) {
2840
+ observer.onNext(left);
2841
+ }
2842
+ }, observer.onError.bind(observer), function () {
2843
+ if (isOpen) {
2844
+ observer.onCompleted();
2845
+ }
2846
+ }));
2847
+
2848
+ var rightSubscription = new SingleAssignmentDisposable();
2849
+ disposables.add(rightSubscription);
2850
+ rightSubscription.setDisposable(other.subscribe(function () {
2851
+ isOpen = true;
2852
+ rightSubscription.dispose();
2853
+ }, observer.onError.bind(observer), function () {
2854
+ rightSubscription.dispose();
2855
+ }));
2856
+
2857
+ return disposables;
2858
+ });
2859
+ };
2860
+
2861
+ /**
2862
+ * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
2863
+ * @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.
2864
+ */
2865
+ observableProto['switch'] = observableProto.switchLatest = function () {
2866
+ var sources = this;
2867
+ return new AnonymousObservable(function (observer) {
2868
+ var hasLatest = false,
2869
+ innerSubscription = new SerialDisposable(),
2870
+ isStopped = false,
2871
+ latest = 0,
2872
+ subscription = sources.subscribe(function (innerSource) {
2873
+ var d = new SingleAssignmentDisposable(), id = ++latest;
2874
+ hasLatest = true;
2875
+ innerSubscription.setDisposable(d);
2876
+ d.setDisposable(innerSource.subscribe(function (x) {
2877
+ if (latest === id) {
2878
+ observer.onNext(x);
2879
+ }
2880
+ }, function (e) {
2881
+ if (latest === id) {
2882
+ observer.onError(e);
2883
+ }
2884
+ }, function () {
2885
+ if (latest === id) {
2886
+ hasLatest = false;
2887
+ if (isStopped) {
2888
+ observer.onCompleted();
2889
+ }
2890
+ }
2891
+ }));
2892
+ }, observer.onError.bind(observer), function () {
2893
+ isStopped = true;
2894
+ if (!hasLatest) {
2895
+ observer.onCompleted();
2896
+ }
2897
+ });
2898
+ return new CompositeDisposable(subscription, innerSubscription);
2899
+ });
2900
+ };
2901
+
2902
+ /**
2903
+ * Returns the values from the source observable sequence until the other observable sequence produces a value.
2904
+ * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
2905
+ * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
2906
+ */
2907
+ observableProto.takeUntil = function (other) {
2908
+ var source = this;
2909
+ return new AnonymousObservable(function (observer) {
2910
+ return new CompositeDisposable(
2911
+ source.subscribe(observer),
2912
+ other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
2913
+ );
2914
+ });
2915
+ };
2916
+
2917
+ function zipArray(second, resultSelector) {
2918
+ var first = this;
2919
+ return new AnonymousObservable(function (observer) {
2920
+ var index = 0, len = second.length;
2921
+ return first.subscribe(function (left) {
2922
+ if (index < len) {
2923
+ var right = second[index++], result;
2924
+ try {
2925
+ result = resultSelector(left, right);
2926
+ } catch (e) {
2927
+ observer.onError(e);
2928
+ return;
2929
+ }
2930
+ observer.onNext(result);
2931
+ } else {
2932
+ observer.onCompleted();
2933
+ }
2934
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
2935
+ });
2936
+ }
2937
+
2938
+ /**
2939
+ * 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.
2940
+ * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
2941
+ *
2942
+ * @example
2943
+ * 1 - res = obs1.zip(obs2, fn);
2944
+ * 1 - res = x1.zip([1,2,3], fn);
2945
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
2946
+ */
2947
+ observableProto.zip = function () {
2948
+ if (Array.isArray(arguments[0])) {
2949
+ return zipArray.apply(this, arguments);
2950
+ }
2951
+ var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
2952
+ sources.unshift(parent);
2953
+ return new AnonymousObservable(function (observer) {
2954
+ var n = sources.length,
2955
+ queues = arrayInitialize(n, function () { return []; }),
2956
+ isDone = arrayInitialize(n, function () { return false; });
2957
+
2958
+ var next = function (i) {
2959
+ var res, queuedValues;
2960
+ if (queues.every(function (x) { return x.length > 0; })) {
2961
+ try {
2962
+ queuedValues = queues.map(function (x) { return x.shift(); });
2963
+ res = resultSelector.apply(parent, queuedValues);
2964
+ } catch (ex) {
2965
+ observer.onError(ex);
2966
+ return;
2967
+ }
2968
+ observer.onNext(res);
2969
+ } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
2970
+ observer.onCompleted();
2971
+ }
2972
+ };
2973
+
2974
+ function done(i) {
2975
+ isDone[i] = true;
2976
+ if (isDone.every(function (x) { return x; })) {
2977
+ observer.onCompleted();
2978
+ }
2979
+ }
2980
+
2981
+ var subscriptions = new Array(n);
2982
+ for (var idx = 0; idx < n; idx++) {
2983
+ (function (i) {
2984
+ subscriptions[i] = new SingleAssignmentDisposable();
2985
+ subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
2986
+ queues[i].push(x);
2987
+ next(i);
2988
+ }, observer.onError.bind(observer), function () {
2989
+ done(i);
2990
+ }));
2991
+ })(idx);
2992
+ }
2993
+
2994
+ return new CompositeDisposable(subscriptions);
2995
+ });
2996
+ };
2997
+ /**
2998
+ * 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.
2999
+ * @param arguments Observable sources.
3000
+ * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
3001
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
3002
+ */
3003
+ Observable.zip = function () {
3004
+ var args = slice.call(arguments, 0),
3005
+ first = args.shift();
3006
+ return first.zip.apply(first, args);
3007
+ };
3008
+
3009
+ /**
3010
+ * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
3011
+ * @param arguments Observable sources.
3012
+ * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
3013
+ */
3014
+ Observable.zipArray = function () {
3015
+ var sources = slice.call(arguments);
3016
+ return new AnonymousObservable(function (observer) {
3017
+ var n = sources.length,
3018
+ queues = arrayInitialize(n, function () { return []; }),
3019
+ isDone = arrayInitialize(n, function () { return false; });
3020
+
3021
+ function next(i) {
3022
+ if (queues.every(function (x) { return x.length > 0; })) {
3023
+ var res = queues.map(function (x) { return x.shift(); });
3024
+ observer.onNext(res);
3025
+ } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
3026
+ observer.onCompleted();
3027
+ return;
3028
+ }
3029
+ };
3030
+
3031
+ function done(i) {
3032
+ isDone[i] = true;
3033
+ if (isDone.every(identity)) {
3034
+ observer.onCompleted();
3035
+ return;
3036
+ }
3037
+ }
3038
+
3039
+ var subscriptions = new Array(n);
3040
+ for (var idx = 0; idx < n; idx++) {
3041
+ (function (i) {
3042
+ subscriptions[i] = new SingleAssignmentDisposable();
3043
+ subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
3044
+ queues[i].push(x);
3045
+ next(i);
3046
+ }, observer.onError.bind(observer), function () {
3047
+ done(i);
3048
+ }));
3049
+ })(idx);
3050
+ }
3051
+
3052
+ var compositeDisposable = new CompositeDisposable(subscriptions);
3053
+ compositeDisposable.add(disposableCreate(function () {
3054
+ for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
3055
+ queues[qIdx] = [];
3056
+ }
3057
+ }));
3058
+ return compositeDisposable;
3059
+ });
3060
+ };
3061
+
3062
+ /**
3063
+ * Hides the identity of an observable sequence.
3064
+ * @returns {Observable} An observable sequence that hides the identity of the source sequence.
3065
+ */
3066
+ observableProto.asObservable = function () {
3067
+ var source = this;
3068
+ return new AnonymousObservable(function (observer) {
3069
+ return source.subscribe(observer);
3070
+ });
3071
+ };
3072
+
3073
+ /**
3074
+ * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
3075
+ *
3076
+ * @example
3077
+ * var res = xs.bufferWithCount(10);
3078
+ * var res = xs.bufferWithCount(10, 1);
3079
+ * @param {Number} count Length of each buffer.
3080
+ * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
3081
+ * @returns {Observable} An observable sequence of buffers.
3082
+ */
3083
+ observableProto.bufferWithCount = function (count, skip) {
3084
+ if (arguments.length === 1) {
3085
+ skip = count;
3086
+ }
3087
+ return this.windowWithCount(count, skip).selectMany(function (x) {
3088
+ return x.toArray();
3089
+ }).where(function (x) {
3090
+ return x.length > 0;
3091
+ });
3092
+ };
3093
+
3094
+ /**
3095
+ * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
3096
+ * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
3097
+ */
3098
+ observableProto.dematerialize = function () {
3099
+ var source = this;
3100
+ return new AnonymousObservable(function (observer) {
3101
+ return source.subscribe(function (x) {
3102
+ return x.accept(observer);
3103
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3104
+ });
3105
+ };
3106
+
3107
+ /**
3108
+ * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
3109
+ *
3110
+ * var obs = observable.distinctUntilChanged();
3111
+ * var obs = observable.distinctUntilChanged(function (x) { return x.id; });
3112
+ * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
3113
+ *
3114
+ * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
3115
+ * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
3116
+ * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
3117
+ */
3118
+ observableProto.distinctUntilChanged = function (keySelector, comparer) {
3119
+ var source = this;
3120
+ keySelector || (keySelector = identity);
3121
+ comparer || (comparer = defaultComparer);
3122
+ return new AnonymousObservable(function (observer) {
3123
+ var hasCurrentKey = false, currentKey;
3124
+ return source.subscribe(function (value) {
3125
+ var comparerEquals = false, key;
3126
+ try {
3127
+ key = keySelector(value);
3128
+ } catch (exception) {
3129
+ observer.onError(exception);
3130
+ return;
3131
+ }
3132
+ if (hasCurrentKey) {
3133
+ try {
3134
+ comparerEquals = comparer(currentKey, key);
3135
+ } catch (exception) {
3136
+ observer.onError(exception);
3137
+ return;
3138
+ }
3139
+ }
3140
+ if (!hasCurrentKey || !comparerEquals) {
3141
+ hasCurrentKey = true;
3142
+ currentKey = key;
3143
+ observer.onNext(value);
3144
+ }
3145
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3146
+ });
3147
+ };
3148
+
3149
+ /**
3150
+ * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
3151
+ * 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.
3152
+ *
3153
+ * @example
3154
+ * var res = observable.doAction(observer);
3155
+ * var res = observable.doAction(onNext);
3156
+ * var res = observable.doAction(onNext, onError);
3157
+ * var res = observable.doAction(onNext, onError, onCompleted);
3158
+ * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
3159
+ * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
3160
+ * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
3161
+ * @returns {Observable} The source sequence with the side-effecting behavior applied.
3162
+ */
3163
+ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
3164
+ var source = this, onNextFunc;
3165
+ if (typeof observerOrOnNext === 'function') {
3166
+ onNextFunc = observerOrOnNext;
3167
+ } else {
3168
+ onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
3169
+ onError = observerOrOnNext.onError.bind(observerOrOnNext);
3170
+ onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
3171
+ }
3172
+ return new AnonymousObservable(function (observer) {
3173
+ return source.subscribe(function (x) {
3174
+ try {
3175
+ onNextFunc(x);
3176
+ } catch (e) {
3177
+ observer.onError(e);
3178
+ }
3179
+ observer.onNext(x);
3180
+ }, function (exception) {
3181
+ if (!onError) {
3182
+ observer.onError(exception);
3183
+ } else {
3184
+ try {
3185
+ onError(exception);
3186
+ } catch (e) {
3187
+ observer.onError(e);
3188
+ }
3189
+ observer.onError(exception);
3190
+ }
3191
+ }, function () {
3192
+ if (!onCompleted) {
3193
+ observer.onCompleted();
3194
+ } else {
3195
+ try {
3196
+ onCompleted();
3197
+ } catch (e) {
3198
+ observer.onError(e);
3199
+ }
3200
+ observer.onCompleted();
3201
+ }
3202
+ });
3203
+ });
3204
+ };
3205
+
3206
+ /**
3207
+ * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
3208
+ *
3209
+ * @example
3210
+ * var res = observable.finallyAction(function () { console.log('sequence ended'; });
3211
+ * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
3212
+ * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
3213
+ */
3214
+ observableProto['finally'] = observableProto.finallyAction = function (action) {
3215
+ var source = this;
3216
+ return new AnonymousObservable(function (observer) {
3217
+ var subscription = source.subscribe(observer);
3218
+ return disposableCreate(function () {
3219
+ try {
3220
+ subscription.dispose();
3221
+ } catch (e) {
3222
+ throw e;
3223
+ } finally {
3224
+ action();
3225
+ }
3226
+ });
3227
+ });
3228
+ };
3229
+
3230
+ /**
3231
+ * Ignores all elements in an observable sequence leaving only the termination messages.
3232
+ * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
3233
+ */
3234
+ observableProto.ignoreElements = function () {
3235
+ var source = this;
3236
+ return new AnonymousObservable(function (observer) {
3237
+ return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3238
+ });
3239
+ };
3240
+
3241
+ /**
3242
+ * Materializes the implicit notifications of an observable sequence as explicit notification values.
3243
+ * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
3244
+ */
3245
+ observableProto.materialize = function () {
3246
+ var source = this;
3247
+ return new AnonymousObservable(function (observer) {
3248
+ return source.subscribe(function (value) {
3249
+ observer.onNext(notificationCreateOnNext(value));
3250
+ }, function (e) {
3251
+ observer.onNext(notificationCreateOnError(e));
3252
+ observer.onCompleted();
3253
+ }, function () {
3254
+ observer.onNext(notificationCreateOnCompleted());
3255
+ observer.onCompleted();
3256
+ });
3257
+ });
3258
+ };
3259
+
3260
+ /**
3261
+ * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
3262
+ *
3263
+ * @example
3264
+ * var res = repeated = source.repeat();
3265
+ * var res = repeated = source.repeat(42);
3266
+ * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
3267
+ * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
3268
+ */
3269
+ observableProto.repeat = function (repeatCount) {
3270
+ return enumerableRepeat(this, repeatCount).concat();
3271
+ };
3272
+
3273
+ /**
3274
+ * 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.
3275
+ *
3276
+ * @example
3277
+ * var res = retried = retry.repeat();
3278
+ * var res = retried = retry.repeat(42);
3279
+ * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
3280
+ * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
3281
+ */
3282
+ observableProto.retry = function (retryCount) {
3283
+ return enumerableRepeat(this, retryCount).catchException();
3284
+ };
3285
+
3286
+ /**
3287
+ * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
3288
+ * For aggregation behavior with no intermediate results, see Observable.aggregate.
3289
+ * @example
3290
+ * var res = source.scan(function (acc, x) { return acc + x; });
3291
+ * var res = source.scan(0, function (acc, x) { return acc + x; });
3292
+ * @param {Mixed} [seed] The initial accumulator value.
3293
+ * @param {Function} accumulator An accumulator function to be invoked on each element.
3294
+ * @returns {Observable} An observable sequence containing the accumulated values.
3295
+ */
3296
+ observableProto.scan = function () {
3297
+ var hasSeed = false, seed, accumulator, source = this;
3298
+ if (arguments.length === 2) {
3299
+ hasSeed = true;
3300
+ seed = arguments[0];
3301
+ accumulator = arguments[1];
3302
+ } else {
3303
+ accumulator = arguments[0];
3304
+ }
3305
+ return new AnonymousObservable(function (observer) {
3306
+ var hasAccumulation, accumulation, hasValue;
3307
+ return source.subscribe (
3308
+ function (x) {
3309
+ try {
3310
+ if (!hasValue) {
3311
+ hasValue = true;
3312
+ }
3313
+
3314
+ if (hasAccumulation) {
3315
+ accumulation = accumulator(accumulation, x);
3316
+ } else {
3317
+ accumulation = hasSeed ? accumulator(seed, x) : x;
3318
+ hasAccumulation = true;
3319
+ }
3320
+ } catch (e) {
3321
+ observer.onError(e);
3322
+ return;
3323
+ }
3324
+
3325
+ observer.onNext(accumulation);
3326
+ },
3327
+ observer.onError.bind(observer),
3328
+ function () {
3329
+ if (!hasValue && hasSeed) {
3330
+ observer.onNext(seed);
3331
+ }
3332
+ observer.onCompleted();
3333
+ }
3334
+ );
3335
+ });
3336
+ };
3337
+
3338
+ /**
3339
+ * Bypasses a specified number of elements at the end of an observable sequence.
3340
+ * @description
3341
+ * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
3342
+ * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
3343
+ * @param count Number of elements to bypass at the end of the source sequence.
3344
+ * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
3345
+ */
3346
+ observableProto.skipLast = function (count) {
3347
+ var source = this;
3348
+ return new AnonymousObservable(function (observer) {
3349
+ var q = [];
3350
+ return source.subscribe(function (x) {
3351
+ q.push(x);
3352
+ if (q.length > count) {
3353
+ observer.onNext(q.shift());
3354
+ }
3355
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3356
+ });
3357
+ };
3358
+
3359
+ /**
3360
+ * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
3361
+ *
3362
+ * var res = source.startWith(1, 2, 3);
3363
+ * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
3364
+ *
3365
+ * @memberOf Observable#
3366
+ * @returns {Observable} The source sequence prepended with the specified values.
3367
+ */
3368
+ observableProto.startWith = function () {
3369
+ var values, scheduler, start = 0;
3370
+ if (!!arguments.length && 'now' in Object(arguments[0])) {
3371
+ scheduler = arguments[0];
3372
+ start = 1;
3373
+ } else {
3374
+ scheduler = immediateScheduler;
3375
+ }
3376
+ values = slice.call(arguments, start);
3377
+ return enumerableFor([observableFromArray(values, scheduler), this]).concat();
3378
+ };
3379
+
3380
+ /**
3381
+ * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
3382
+ *
3383
+ * @example
3384
+ * var res = source.takeLast(5);
3385
+ * var res = source.takeLast(5, Rx.Scheduler.timeout);
3386
+ *
3387
+ * @description
3388
+ * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
3389
+ * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
3390
+ * @param {Number} count Number of elements to take from the end of the source sequence.
3391
+ * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
3392
+ * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
3393
+ */
3394
+ observableProto.takeLast = function (count, scheduler) {
3395
+ return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
3396
+ };
3397
+
3398
+ /**
3399
+ * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
3400
+ *
3401
+ * @description
3402
+ * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
3403
+ * source sequence, this buffer is produced on the result sequence.
3404
+ * @param {Number} count Number of elements to take from the end of the source sequence.
3405
+ * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
3406
+ */
3407
+ observableProto.takeLastBuffer = function (count) {
3408
+ var source = this;
3409
+ return new AnonymousObservable(function (observer) {
3410
+ var q = [];
3411
+ return source.subscribe(function (x) {
3412
+ q.push(x);
3413
+ if (q.length > count) {
3414
+ q.shift();
3415
+ }
3416
+ }, observer.onError.bind(observer), function () {
3417
+ observer.onNext(q);
3418
+ observer.onCompleted();
3419
+ });
3420
+ });
3421
+ };
3422
+
3423
+ /**
3424
+ * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
3425
+ *
3426
+ * var res = xs.windowWithCount(10);
3427
+ * var res = xs.windowWithCount(10, 1);
3428
+ * @param {Number} count Length of each window.
3429
+ * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
3430
+ * @returns {Observable} An observable sequence of windows.
3431
+ */
3432
+ observableProto.windowWithCount = function (count, skip) {
3433
+ var source = this;
3434
+ if (count <= 0) {
3435
+ throw new Error(argumentOutOfRange);
3436
+ }
3437
+ if (arguments.length === 1) {
3438
+ skip = count;
3439
+ }
3440
+ if (skip <= 0) {
3441
+ throw new Error(argumentOutOfRange);
3442
+ }
3443
+ return new AnonymousObservable(function (observer) {
3444
+ var m = new SingleAssignmentDisposable(),
3445
+ refCountDisposable = new RefCountDisposable(m),
3446
+ n = 0,
3447
+ q = [],
3448
+ createWindow = function () {
3449
+ var s = new Subject();
3450
+ q.push(s);
3451
+ observer.onNext(addRef(s, refCountDisposable));
3452
+ };
3453
+ createWindow();
3454
+ m.setDisposable(source.subscribe(function (x) {
3455
+ var s;
3456
+ for (var i = 0, len = q.length; i < len; i++) {
3457
+ q[i].onNext(x);
3458
+ }
3459
+ var c = n - count + 1;
3460
+ if (c >= 0 && c % skip === 0) {
3461
+ s = q.shift();
3462
+ s.onCompleted();
3463
+ }
3464
+ n++;
3465
+ if (n % skip === 0) {
3466
+ createWindow();
3467
+ }
3468
+ }, function (exception) {
3469
+ while (q.length > 0) {
3470
+ q.shift().onError(exception);
3471
+ }
3472
+ observer.onError(exception);
3473
+ }, function () {
3474
+ while (q.length > 0) {
3475
+ q.shift().onCompleted();
3476
+ }
3477
+ observer.onCompleted();
3478
+ }));
3479
+ return refCountDisposable;
3480
+ });
3481
+ };
3482
+
3483
+ /**
3484
+ * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
3485
+ *
3486
+ * var res = obs = xs.defaultIfEmpty();
3487
+ * 2 - obs = xs.defaultIfEmpty(false);
3488
+ *
3489
+ * @memberOf Observable#
3490
+ * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
3491
+ * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
3492
+ */
3493
+ observableProto.defaultIfEmpty = function (defaultValue) {
3494
+ var source = this;
3495
+ if (defaultValue === undefined) {
3496
+ defaultValue = null;
3497
+ }
3498
+ return new AnonymousObservable(function (observer) {
3499
+ var found = false;
3500
+ return source.subscribe(function (x) {
3501
+ found = true;
3502
+ observer.onNext(x);
3503
+ }, observer.onError.bind(observer), function () {
3504
+ if (!found) {
3505
+ observer.onNext(defaultValue);
3506
+ }
3507
+ observer.onCompleted();
3508
+ });
3509
+ });
3510
+ };
3511
+
3512
+ /**
3513
+ * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
3514
+ * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
3515
+ *
3516
+ * @example
3517
+ * var res = obs = xs.distinct();
3518
+ * 2 - obs = xs.distinct(function (x) { return x.id; });
3519
+ * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); });
3520
+ * @param {Function} [keySelector] A function to compute the comparison key for each element.
3521
+ * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
3522
+ * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
3523
+ */
3524
+ observableProto.distinct = function (keySelector, keySerializer) {
3525
+ var source = this;
3526
+ keySelector || (keySelector = identity);
3527
+ keySerializer || (keySerializer = defaultKeySerializer);
3528
+ return new AnonymousObservable(function (observer) {
3529
+ var hashSet = {};
3530
+ return source.subscribe(function (x) {
3531
+ var key, serializedKey, otherKey, hasMatch = false;
3532
+ try {
3533
+ key = keySelector(x);
3534
+ serializedKey = keySerializer(key);
3535
+ } catch (exception) {
3536
+ observer.onError(exception);
3537
+ return;
3538
+ }
3539
+ for (otherKey in hashSet) {
3540
+ if (serializedKey === otherKey) {
3541
+ hasMatch = true;
3542
+ break;
3543
+ }
3544
+ }
3545
+ if (!hasMatch) {
3546
+ hashSet[serializedKey] = null;
3547
+ observer.onNext(x);
3548
+ }
3549
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3550
+ });
3551
+ };
3552
+
3553
+ /**
3554
+ * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
3555
+ *
3556
+ * @example
3557
+ * var res = observable.groupBy(function (x) { return x.id; });
3558
+ * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
3559
+ * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
3560
+ * @param {Function} keySelector A function to extract the key for each element.
3561
+ * @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
3562
+ * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
3563
+ * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
3564
+ */
3565
+ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) {
3566
+ return this.groupByUntil(keySelector, elementSelector, function () {
3567
+ return observableNever();
3568
+ }, keySerializer);
3569
+ };
3570
+
3571
+ /**
3572
+ * Groups the elements of an observable sequence according to a specified key selector function.
3573
+ * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
3574
+ * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
3575
+ *
3576
+ * @example
3577
+ * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
3578
+ * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
3579
+ * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
3580
+ * @param {Function} keySelector A function to extract the key for each element.
3581
+ * @param {Function} durationSelector A function to signal the expiration of a group.
3582
+ * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
3583
+ * @returns {Observable}
3584
+ * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
3585
+ * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
3586
+ *
3587
+ */
3588
+ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) {
3589
+ var source = this;
3590
+ elementSelector || (elementSelector = identity);
3591
+ keySerializer || (keySerializer = defaultKeySerializer);
3592
+ return new AnonymousObservable(function (observer) {
3593
+ var map = {},
3594
+ groupDisposable = new CompositeDisposable(),
3595
+ refCountDisposable = new RefCountDisposable(groupDisposable);
3596
+ groupDisposable.add(source.subscribe(function (x) {
3597
+ var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w;
3598
+ try {
3599
+ key = keySelector(x);
3600
+ serializedKey = keySerializer(key);
3601
+ } catch (e) {
3602
+ for (w in map) {
3603
+ map[w].onError(e);
3604
+ }
3605
+ observer.onError(e);
3606
+ return;
3607
+ }
3608
+ fireNewMapEntry = false;
3609
+ try {
3610
+ writer = map[serializedKey];
3611
+ if (!writer) {
3612
+ writer = new Subject();
3613
+ map[serializedKey] = writer;
3614
+ fireNewMapEntry = true;
3615
+ }
3616
+ } catch (e) {
3617
+ for (w in map) {
3618
+ map[w].onError(e);
3619
+ }
3620
+ observer.onError(e);
3621
+ return;
3622
+ }
3623
+ if (fireNewMapEntry) {
3624
+ group = new GroupedObservable(key, writer, refCountDisposable);
3625
+ durationGroup = new GroupedObservable(key, writer);
3626
+ try {
3627
+ duration = durationSelector(durationGroup);
3628
+ } catch (e) {
3629
+ for (w in map) {
3630
+ map[w].onError(e);
3631
+ }
3632
+ observer.onError(e);
3633
+ return;
3634
+ }
3635
+ observer.onNext(group);
3636
+ md = new SingleAssignmentDisposable();
3637
+ groupDisposable.add(md);
3638
+ var expire = function () {
3639
+ if (serializedKey in map) {
3640
+ delete map[serializedKey];
3641
+ writer.onCompleted();
3642
+ }
3643
+ groupDisposable.remove(md);
3644
+ };
3645
+ md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
3646
+ for (w in map) {
3647
+ map[w].onError(exn);
3648
+ }
3649
+ observer.onError(exn);
3650
+ }, function () {
3651
+ expire();
3652
+ }));
3653
+ }
3654
+ try {
3655
+ element = elementSelector(x);
3656
+ } catch (e) {
3657
+ for (w in map) {
3658
+ map[w].onError(e);
3659
+ }
3660
+ observer.onError(e);
3661
+ return;
3662
+ }
3663
+ writer.onNext(element);
3664
+ }, function (ex) {
3665
+ for (var w in map) {
3666
+ map[w].onError(ex);
3667
+ }
3668
+ observer.onError(ex);
3669
+ }, function () {
3670
+ for (var w in map) {
3671
+ map[w].onCompleted();
3672
+ }
3673
+ observer.onCompleted();
3674
+ }));
3675
+ return refCountDisposable;
3676
+ });
3677
+ };
3678
+
3679
+ /**
3680
+ * Projects each element of an observable sequence into a new form by incorporating the element's index.
3681
+ * @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.
3682
+ * @param {Any} [thisArg] Object to use as this when executing callback.
3683
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
3684
+ */
3685
+ observableProto.select = observableProto.map = function (selector, thisArg) {
3686
+ var parent = this;
3687
+ return new AnonymousObservable(function (observer) {
3688
+ var count = 0;
3689
+ return parent.subscribe(function (value) {
3690
+ var result;
3691
+ try {
3692
+ result = selector.call(thisArg, value, count++, parent);
3693
+ } catch (exception) {
3694
+ observer.onError(exception);
3695
+ return;
3696
+ }
3697
+ observer.onNext(result);
3698
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3699
+ });
3700
+ };
3701
+
3702
+ /**
3703
+ * Retrieves the value of a specified property from all elements in the Observable sequence.
3704
+ * @param {String} property The property to pluck.
3705
+ * @returns {Observable} Returns a new Observable sequence of property values.
3706
+ */
3707
+ observableProto.pluck = function (property) {
3708
+ return this.select(function (x) { return x[property]; });
3709
+ };
3710
+
3711
+ function selectMany(selector) {
3712
+ return this.select(selector).mergeObservable();
3713
+ }
3714
+
3715
+ /**
3716
+ * One of the Following:
3717
+ * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
3718
+ *
3719
+ * @example
3720
+ * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
3721
+ * Or:
3722
+ * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
3723
+ *
3724
+ * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
3725
+ * Or:
3726
+ * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
3727
+ *
3728
+ * var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
3729
+ * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
3730
+ * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
3731
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
3732
+ */
3733
+ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
3734
+ if (resultSelector) {
3735
+ return this.selectMany(function (x) {
3736
+ return selector(x).select(function (y) {
3737
+ return resultSelector(x, y);
3738
+ });
3739
+ });
3740
+ }
3741
+ if (typeof selector === 'function') {
3742
+ return selectMany.call(this, selector);
3743
+ }
3744
+ return selectMany.call(this, function () {
3745
+ return selector;
3746
+ });
3747
+ };
3748
+
3749
+ /**
3750
+ * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
3751
+ * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
3752
+ * @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.
3753
+ * @param {Any} [thisArg] Object to use as this when executing callback.
3754
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
3755
+ * and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
3756
+ */
3757
+ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
3758
+ return this.select(selector, thisArg).switchLatest();
3759
+ };
3760
+
3761
+ /**
3762
+ * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
3763
+ * @param {Number} count The number of elements to skip before returning the remaining elements.
3764
+ * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
3765
+ */
3766
+ observableProto.skip = function (count) {
3767
+ if (count < 0) {
3768
+ throw new Error(argumentOutOfRange);
3769
+ }
3770
+ var observable = this;
3771
+ return new AnonymousObservable(function (observer) {
3772
+ var remaining = count;
3773
+ return observable.subscribe(function (x) {
3774
+ if (remaining <= 0) {
3775
+ observer.onNext(x);
3776
+ } else {
3777
+ remaining--;
3778
+ }
3779
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3780
+ });
3781
+ };
3782
+
3783
+ /**
3784
+ * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
3785
+ * The element's index is used in the logic of the predicate function.
3786
+ *
3787
+ * var res = source.skipWhile(function (value) { return value < 10; });
3788
+ * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
3789
+ * @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.
3790
+ * @param {Any} [thisArg] Object to use as this when executing callback.
3791
+ * @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.
3792
+ */
3793
+ observableProto.skipWhile = function (predicate, thisArg) {
3794
+ var source = this;
3795
+ return new AnonymousObservable(function (observer) {
3796
+ var i = 0, running = false;
3797
+ return source.subscribe(function (x) {
3798
+ if (!running) {
3799
+ try {
3800
+ running = !predicate.call(thisArg, x, i++, source);
3801
+ } catch (e) {
3802
+ observer.onError(e);
3803
+ return;
3804
+ }
3805
+ }
3806
+ if (running) {
3807
+ observer.onNext(x);
3808
+ }
3809
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3810
+ });
3811
+ };
3812
+
3813
+ /**
3814
+ * 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).
3815
+ *
3816
+ * var res = source.take(5);
3817
+ * var res = source.take(0, Rx.Scheduler.timeout);
3818
+ * @param {Number} count The number of elements to return.
3819
+ * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
3820
+ * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
3821
+ */
3822
+ observableProto.take = function (count, scheduler) {
3823
+ if (count < 0) {
3824
+ throw new Error(argumentOutOfRange);
3825
+ }
3826
+ if (count === 0) {
3827
+ return observableEmpty(scheduler);
3828
+ }
3829
+ var observable = this;
3830
+ return new AnonymousObservable(function (observer) {
3831
+ var remaining = count;
3832
+ return observable.subscribe(function (x) {
3833
+ if (remaining > 0) {
3834
+ remaining--;
3835
+ observer.onNext(x);
3836
+ if (remaining === 0) {
3837
+ observer.onCompleted();
3838
+ }
3839
+ }
3840
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3841
+ });
3842
+ };
3843
+
3844
+ /**
3845
+ * Returns elements from an observable sequence as long as a specified condition is true.
3846
+ * The element's index is used in the logic of the predicate function.
3847
+ *
3848
+ * @example
3849
+ * var res = source.takeWhile(function (value) { return value < 10; });
3850
+ * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
3851
+ * @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.
3852
+ * @param {Any} [thisArg] Object to use as this when executing callback.
3853
+ * @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.
3854
+ */
3855
+ observableProto.takeWhile = function (predicate, thisArg) {
3856
+ var observable = this;
3857
+ return new AnonymousObservable(function (observer) {
3858
+ var i = 0, running = true;
3859
+ return observable.subscribe(function (x) {
3860
+ if (running) {
3861
+ try {
3862
+ running = predicate.call(thisArg, x, i++, observable);
3863
+ } catch (e) {
3864
+ observer.onError(e);
3865
+ return;
3866
+ }
3867
+ if (running) {
3868
+ observer.onNext(x);
3869
+ } else {
3870
+ observer.onCompleted();
3871
+ }
3872
+ }
3873
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3874
+ });
3875
+ };
3876
+
3877
+ /**
3878
+ * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
3879
+ *
3880
+ * @example
3881
+ * var res = source.where(function (value) { return value < 10; });
3882
+ * var res = source.where(function (value, index) { return value < 10 || index < 10; });
3883
+ * @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.
3884
+ * @param {Any} [thisArg] Object to use as this when executing callback.
3885
+ * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
3886
+ */
3887
+ observableProto.where = observableProto.filter = function (predicate, thisArg) {
3888
+ var parent = this;
3889
+ return new AnonymousObservable(function (observer) {
3890
+ var count = 0;
3891
+ return parent.subscribe(function (value) {
3892
+ var shouldRun;
3893
+ try {
3894
+ shouldRun = predicate.call(thisArg, value, count++, parent);
3895
+ } catch (exception) {
3896
+ observer.onError(exception);
3897
+ return;
3898
+ }
3899
+ if (shouldRun) {
3900
+ observer.onNext(value);
3901
+ }
3902
+ }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
3903
+ });
3904
+ };
3905
+
3906
+ var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
3907
+ inherits(AnonymousObservable, _super);
3908
+
3909
+ // Fix subscriber to check for undefined or function returned to decorate as Disposable
3910
+ function fixSubscriber(subscriber) {
3911
+ if (typeof subscriber === 'undefined') {
3912
+ subscriber = disposableEmpty;
3913
+ } else if (typeof subscriber === 'function') {
3914
+ subscriber = disposableCreate(subscriber);
3915
+ }
3916
+
3917
+ return subscriber;
3918
+ }
3919
+
3920
+ function AnonymousObservable(subscribe) {
3921
+ if (!(this instanceof AnonymousObservable)) {
3922
+ return new AnonymousObservable(subscribe);
3923
+ }
3924
+
3925
+ function s(observer) {
3926
+ var autoDetachObserver = new AutoDetachObserver(observer);
3927
+ if (currentThreadScheduler.scheduleRequired()) {
3928
+ currentThreadScheduler.schedule(function () {
3929
+ try {
3930
+ autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
3931
+ } catch (e) {
3932
+ if (!autoDetachObserver.fail(e)) {
3933
+ throw e;
3934
+ }
3935
+ }
3936
+ });
3937
+ } else {
3938
+ try {
3939
+ autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
3940
+ } catch (e) {
3941
+ if (!autoDetachObserver.fail(e)) {
3942
+ throw e;
3943
+ }
3944
+ }
3945
+ }
3946
+
3947
+ return autoDetachObserver;
3948
+ }
3949
+
3950
+ _super.call(this, s);
3951
+ }
3952
+
3953
+ return AnonymousObservable;
3954
+
3955
+ }(Observable));
3956
+
3957
+ /** @private */
3958
+ var AutoDetachObserver = (function (_super) {
3959
+ inherits(AutoDetachObserver, _super);
3960
+
3961
+ function AutoDetachObserver(observer) {
3962
+ _super.call(this);
3963
+ this.observer = observer;
3964
+ this.m = new SingleAssignmentDisposable();
3965
+ }
3966
+
3967
+ var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
3968
+
3969
+ AutoDetachObserverPrototype.next = function (value) {
3970
+ var noError = false;
3971
+ try {
3972
+ this.observer.onNext(value);
3973
+ noError = true;
3974
+ } catch (e) {
3975
+ throw e;
3976
+ } finally {
3977
+ if (!noError) {
3978
+ this.dispose();
3979
+ }
3980
+ }
3981
+ };
3982
+
3983
+ AutoDetachObserverPrototype.error = function (exn) {
3984
+ try {
3985
+ this.observer.onError(exn);
3986
+ } catch (e) {
3987
+ throw e;
3988
+ } finally {
3989
+ this.dispose();
3990
+ }
3991
+ };
3992
+
3993
+ AutoDetachObserverPrototype.completed = function () {
3994
+ try {
3995
+ this.observer.onCompleted();
3996
+ } catch (e) {
3997
+ throw e;
3998
+ } finally {
3999
+ this.dispose();
4000
+ }
4001
+ };
4002
+
4003
+ AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
4004
+ AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
4005
+ /* @private */
4006
+ AutoDetachObserverPrototype.disposable = function (value) {
4007
+ return arguments.length ? this.getDisposable() : setDisposable(value);
4008
+ };
4009
+
4010
+ AutoDetachObserverPrototype.dispose = function () {
4011
+ _super.prototype.dispose.call(this);
4012
+ this.m.dispose();
4013
+ };
4014
+
4015
+ return AutoDetachObserver;
4016
+ }(AbstractObserver));
4017
+
4018
+ /** @private */
4019
+ var GroupedObservable = (function (_super) {
4020
+ inherits(GroupedObservable, _super);
4021
+
4022
+ function subscribe(observer) {
4023
+ return this.underlyingObservable.subscribe(observer);
4024
+ }
4025
+
4026
+ /**
4027
+ * @constructor
4028
+ * @private
4029
+ */
4030
+ function GroupedObservable(key, underlyingObservable, mergedDisposable) {
4031
+ _super.call(this, subscribe);
4032
+ this.key = key;
4033
+ this.underlyingObservable = !mergedDisposable ?
4034
+ underlyingObservable :
4035
+ new AnonymousObservable(function (observer) {
4036
+ return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
4037
+ });
4038
+ }
4039
+
4040
+ return GroupedObservable;
4041
+ }(Observable));
4042
+
4043
+ /** @private */
4044
+ var InnerSubscription = function (subject, observer) {
4045
+ this.subject = subject;
4046
+ this.observer = observer;
4047
+ };
4048
+
4049
+ /**
4050
+ * @private
4051
+ * @memberOf InnerSubscription
4052
+ */
4053
+ InnerSubscription.prototype.dispose = function () {
4054
+ if (!this.subject.isDisposed && this.observer !== null) {
4055
+ var idx = this.subject.observers.indexOf(this.observer);
4056
+ this.subject.observers.splice(idx, 1);
4057
+ this.observer = null;
4058
+ }
4059
+ };
4060
+
4061
+ /**
4062
+ * Represents an object that is both an observable sequence as well as an observer.
4063
+ * Each notification is broadcasted to all subscribed observers.
4064
+ */
4065
+ var Subject = Rx.Subject = (function (_super) {
4066
+ function subscribe(observer) {
4067
+ checkDisposed.call(this);
4068
+ if (!this.isStopped) {
4069
+ this.observers.push(observer);
4070
+ return new InnerSubscription(this, observer);
4071
+ }
4072
+ if (this.exception) {
4073
+ observer.onError(this.exception);
4074
+ return disposableEmpty;
4075
+ }
4076
+ observer.onCompleted();
4077
+ return disposableEmpty;
4078
+ }
4079
+
4080
+ inherits(Subject, _super);
4081
+
4082
+ /**
4083
+ * Creates a subject.
4084
+ * @constructor
4085
+ */
4086
+ function Subject() {
4087
+ _super.call(this, subscribe);
4088
+ this.isDisposed = false,
4089
+ this.isStopped = false,
4090
+ this.observers = [];
4091
+ }
4092
+
4093
+ addProperties(Subject.prototype, Observer, {
4094
+ /**
4095
+ * Indicates whether the subject has observers subscribed to it.
4096
+ * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
4097
+ */
4098
+ hasObservers: function () {
4099
+ return this.observers.length > 0;
4100
+ },
4101
+ /**
4102
+ * Notifies all subscribed observers about the end of the sequence.
4103
+ */
4104
+ onCompleted: function () {
4105
+ checkDisposed.call(this);
4106
+ if (!this.isStopped) {
4107
+ var os = this.observers.slice(0);
4108
+ this.isStopped = true;
4109
+ for (var i = 0, len = os.length; i < len; i++) {
4110
+ os[i].onCompleted();
4111
+ }
4112
+
4113
+ this.observers = [];
4114
+ }
4115
+ },
4116
+ /**
4117
+ * Notifies all subscribed observers about the exception.
4118
+ * @param {Mixed} error The exception to send to all observers.
4119
+ */
4120
+ onError: function (exception) {
4121
+ checkDisposed.call(this);
4122
+ if (!this.isStopped) {
4123
+ var os = this.observers.slice(0);
4124
+ this.isStopped = true;
4125
+ this.exception = exception;
4126
+ for (var i = 0, len = os.length; i < len; i++) {
4127
+ os[i].onError(exception);
4128
+ }
4129
+
4130
+ this.observers = [];
4131
+ }
4132
+ },
4133
+ /**
4134
+ * Notifies all subscribed observers about the arrival of the specified element in the sequence.
4135
+ * @param {Mixed} value The value to send to all observers.
4136
+ */
4137
+ onNext: function (value) {
4138
+ checkDisposed.call(this);
4139
+ if (!this.isStopped) {
4140
+ var os = this.observers.slice(0);
4141
+ for (var i = 0, len = os.length; i < len; i++) {
4142
+ os[i].onNext(value);
4143
+ }
4144
+ }
4145
+ },
4146
+ /**
4147
+ * Unsubscribe all observers and release resources.
4148
+ */
4149
+ dispose: function () {
4150
+ this.isDisposed = true;
4151
+ this.observers = null;
4152
+ }
4153
+ });
4154
+
4155
+ /**
4156
+ * Creates a subject from the specified observer and observable.
4157
+ * @param {Observer} observer The observer used to send messages to the subject.
4158
+ * @param {Observable} observable The observable used to subscribe to messages sent from the subject.
4159
+ * @returns {Subject} Subject implemented using the given observer and observable.
4160
+ */
4161
+ Subject.create = function (observer, observable) {
4162
+ return new AnonymousSubject(observer, observable);
4163
+ };
4164
+
4165
+ return Subject;
4166
+ }(Observable));
4167
+
4168
+ /**
4169
+ * Represents the result of an asynchronous operation.
4170
+ * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
4171
+ */
4172
+ var AsyncSubject = Rx.AsyncSubject = (function (_super) {
4173
+
4174
+ function subscribe(observer) {
4175
+ checkDisposed.call(this);
4176
+ if (!this.isStopped) {
4177
+ this.observers.push(observer);
4178
+ return new InnerSubscription(this, observer);
4179
+ }
4180
+ var ex = this.exception;
4181
+ var hv = this.hasValue;
4182
+ var v = this.value;
4183
+ if (ex) {
4184
+ observer.onError(ex);
4185
+ } else if (hv) {
4186
+ observer.onNext(v);
4187
+ observer.onCompleted();
4188
+ } else {
4189
+ observer.onCompleted();
4190
+ }
4191
+ return disposableEmpty;
4192
+ }
4193
+
4194
+ inherits(AsyncSubject, _super);
4195
+
4196
+ /**
4197
+ * Creates a subject that can only receive one value and that value is cached for all future observations.
4198
+ * @constructor
4199
+ */
4200
+ function AsyncSubject() {
4201
+ _super.call(this, subscribe);
4202
+
4203
+ this.isDisposed = false,
4204
+ this.isStopped = false,
4205
+ this.value = null,
4206
+ this.hasValue = false,
4207
+ this.observers = [],
4208
+ this.exception = null;
4209
+ }
4210
+
4211
+ addProperties(AsyncSubject.prototype, Observer, {
4212
+ /**
4213
+ * Indicates whether the subject has observers subscribed to it.
4214
+ * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
4215
+ */
4216
+ hasObservers: function () {
4217
+ return this.observers.length > 0;
4218
+ },
4219
+ /**
4220
+ * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
4221
+ */
4222
+ onCompleted: function () {
4223
+ var o, i, len;
4224
+ checkDisposed.call(this);
4225
+ if (!this.isStopped) {
4226
+ var os = this.observers.slice(0);
4227
+ this.isStopped = true;
4228
+ var v = this.value;
4229
+ var hv = this.hasValue;
4230
+
4231
+ if (hv) {
4232
+ for (i = 0, len = os.length; i < len; i++) {
4233
+ o = os[i];
4234
+ o.onNext(v);
4235
+ o.onCompleted();
4236
+ }
4237
+ } else {
4238
+ for (i = 0, len = os.length; i < len; i++) {
4239
+ os[i].onCompleted();
4240
+ }
4241
+ }
4242
+
4243
+ this.observers = [];
4244
+ }
4245
+ },
4246
+ /**
4247
+ * Notifies all subscribed observers about the exception.
4248
+ * @param {Mixed} error The exception to send to all observers.
4249
+ */
4250
+ onError: function (exception) {
4251
+ checkDisposed.call(this);
4252
+ if (!this.isStopped) {
4253
+ var os = this.observers.slice(0);
4254
+ this.isStopped = true;
4255
+ this.exception = exception;
4256
+
4257
+ for (var i = 0, len = os.length; i < len; i++) {
4258
+ os[i].onError(exception);
4259
+ }
4260
+
4261
+ this.observers = [];
4262
+ }
4263
+ },
4264
+ /**
4265
+ * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
4266
+ * @param {Mixed} value The value to store in the subject.
4267
+ */
4268
+ onNext: function (value) {
4269
+ checkDisposed.call(this);
4270
+ if (!this.isStopped) {
4271
+ this.value = value;
4272
+ this.hasValue = true;
4273
+ }
4274
+ },
4275
+ /**
4276
+ * Unsubscribe all observers and release resources.
4277
+ */
4278
+ dispose: function () {
4279
+ this.isDisposed = true;
4280
+ this.observers = null;
4281
+ this.exception = null;
4282
+ this.value = null;
4283
+ }
4284
+ });
4285
+
4286
+ return AsyncSubject;
4287
+ }(Observable));
4288
+
4289
+ /** @private */
4290
+ var AnonymousSubject = (function (_super) {
4291
+ inherits(AnonymousSubject, _super);
4292
+
4293
+ function subscribe(observer) {
4294
+ return this.observable.subscribe(observer);
4295
+ }
4296
+
4297
+ /**
4298
+ * @private
4299
+ * @constructor
4300
+ */
4301
+ function AnonymousSubject(observer, observable) {
4302
+ _super.call(this, subscribe);
4303
+ this.observer = observer;
4304
+ this.observable = observable;
4305
+ }
4306
+
4307
+ addProperties(AnonymousSubject.prototype, Observer, {
4308
+ /**
4309
+ * @private
4310
+ * @memberOf AnonymousSubject#
4311
+ */
4312
+ onCompleted: function () {
4313
+ this.observer.onCompleted();
4314
+ },
4315
+ /**
4316
+ * @private
4317
+ * @memberOf AnonymousSubject#
4318
+ */
4319
+ onError: function (exception) {
4320
+ this.observer.onError(exception);
4321
+ },
4322
+ /**
4323
+ * @private
4324
+ * @memberOf AnonymousSubject#
4325
+ */
4326
+ onNext: function (value) {
4327
+ this.observer.onNext(value);
4328
+ }
4329
+ });
4330
+
4331
+ return AnonymousSubject;
4332
+ }(Observable));
4333
+
4334
+ if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
4335
+ root.Rx = Rx;
4336
+
4337
+ define(function() {
4338
+ return Rx;
4339
+ });
4340
+ } else if (freeExports && freeModule) {
4341
+ // in Node.js or RingoJS
4342
+ if (moduleExports) {
4343
+ (freeModule.exports = Rx).Rx = Rx;
4344
+ } else {
4345
+ freeExports.Rx = Rx;
4346
+ }
4347
+ } else {
4348
+ // in a browser or Rhino
4349
+ root.Rx = Rx;
4350
+ }
4351
+ }.call(this));