From 915c8425ed0b16c9c4bfc17a5f2b89ec61220326 Mon Sep 17 00:00:00 2001 From: Anler Hernandez Peral Date: Fri, 5 Feb 2016 10:11:45 +0100 Subject: [PATCH] Fancier CounterList --- README.md | 1 + examples/04-list-of-counters/README.md | 12 ++ examples/04-list-of-counters/app.js | 38 ++++ examples/04-list-of-counters/bundle.js | 176 +++++++++++++++++++ examples/04-list-of-counters/counter-list.js | 95 ++++++++++ examples/04-list-of-counters/counter.js | 55 ++++++ examples/04-list-of-counters/index.html | 21 +++ examples/04-list-of-counters/index.js | 4 + package.json | 2 + 9 files changed, 404 insertions(+) create mode 100644 examples/04-list-of-counters/README.md create mode 100644 examples/04-list-of-counters/app.js create mode 100644 examples/04-list-of-counters/bundle.js create mode 100644 examples/04-list-of-counters/counter-list.js create mode 100644 examples/04-list-of-counters/counter.js create mode 100644 examples/04-list-of-counters/index.html create mode 100644 examples/04-list-of-counters/index.js diff --git a/README.md b/README.md index d14e0ed..c37bbb0 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Run any example with `npm run ex`, eg: `npm run ex1` 1. [Simple counter](https://github.com/kaleidos/olmo/blob/master/examples/01-counter) / [demo](http://kaleidos.github.io/olmo/examples/01-counter/) 2. [Counter pair](https://github.com/kaleidos/olmo/blob/master/examples/02-counter-pair) / [demo](http://kaleidos.github.io/olmo/examples/02-counter-pair/) 3. [List of counters](https://github.com/kaleidos/olmo/blob/master/examples/03-list-of-counters) / [demo](http://kaleidos.github.io/olmo/examples/03-list-of-counters/) +4. [Fancier list of counters](https://github.com/kaleidos/olmo/blob/master/examples/04-list-of-counters) / [demo](http://kaleidos.github.io/olmo/examples/04-list-of-counters/) ## Testing ## diff --git a/examples/04-list-of-counters/README.md b/examples/04-list-of-counters/README.md new file mode 100644 index 0000000..96b3e29 --- /dev/null +++ b/examples/04-list-of-counters/README.md @@ -0,0 +1,12 @@ +In this example you can see how to dynamically create and update other components. + +Important points of this example: + +* The use partially applying "action creators" thanks to the use of algebraic data types (ADT): +``` JavaScript +Modify: ['id', 'counterAction'] +... +Action.Modify(id) +``` + +Note: There's not typechecking involve inside of the ADTs, and the strings 'id' and 'counterAction' are attribute names that are going to be present inside the action object passed to the update function. diff --git a/examples/04-list-of-counters/app.js b/examples/04-list-of-counters/app.js new file mode 100644 index 0000000..2be059f --- /dev/null +++ b/examples/04-list-of-counters/app.js @@ -0,0 +1,38 @@ +import StartApp from 'olmo/start-app'; +import Signal from 'olmo/signal'; +import Task from 'olmo/task'; + +import snabbdom from 'snabbdom'; +import snabbdomProps from 'snabbdom/modules/props'; +import snabbdomEvents from 'snabbdom/modules/eventlisteners'; + +import CounterList from './counter-list'; + + +const patch = snabbdom.init([snabbdomProps, snabbdomEvents]); + +function render([oldHtml, newHtml]) { + return Task.of(() => patch(oldHtml, newHtml)); +} + +export default function App() { + var {html, model, tasks} = StartApp.AppSimple({ + init: CounterList.init(), + update: CounterList.update, + view: CounterList.view + }); + + return { + html, + model, + // tasks perform side-effects + tasks: Signal.merge( + tasks, + // rendering is just a side-effect + html + .startWith(document.getElementById('root')) + .pairwise() + .flatMap(render) + ) + }; +} diff --git a/examples/04-list-of-counters/bundle.js b/examples/04-list-of-counters/bundle.js new file mode 100644 index 0000000..a908b74 --- /dev/null +++ b/examples/04-list-of-counters/bundle.js @@ -0,0 +1,176 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + eval("'use strict';\n\nvar _startApp = __webpack_require__(1);\n\nvar _app = __webpack_require__(11);\n\nvar _app2 = _interopRequireDefault(_app);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n(0, _startApp.runApp)((0, _app2.default)());\n\n/*****************\n ** WEBPACK FOOTER\n ** ./examples/04-list-of-counters/index.js\n ** module id = 0\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///./examples/04-list-of-counters/index.js?"); + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + eval("'use strict';\n\nvar _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.runApp = runApp;\nexports.App = App;\nexports.AppSimple = AppSimple;\n\nvar _rx = __webpack_require__(2);\n\nvar _rx2 = _interopRequireDefault(_rx);\n\nvar _ramda = __webpack_require__(5);\n\nvar _ramda2 = _interopRequireDefault(_ramda);\n\nvar _data = __webpack_require__(6);\n\nvar _data2 = _interopRequireDefault(_data);\n\nvar _signal = __webpack_require__(8);\n\nvar _signal2 = _interopRequireDefault(_signal);\n\nvar _effects = __webpack_require__(9);\n\nvar _effects2 = _interopRequireDefault(_effects);\n\nvar _task = __webpack_require__(10);\n\nvar _task2 = _interopRequireDefault(_task);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\n// type Conf model action = { init : (model, Effect action)\n// , update : (action, model) -> (model, Effect action)\n// , view : {Address action, model} -> VirtualDOM\n// , inputs: [Signal action] }\n\n// type App model action = { model : model\n// , tasks : Signal (Task Never ())\n// , html : Signal VirtualDOM }\n\n// runApp : App model action -> RxSubscription\nfunction runApp(app) {\n return _rx2.default.Observable.merge(app.html, app.model, app.tasks).subscribe();\n}\n\n// App : Conf model action -> App model action\nfunction App(config) {\n var _Rx$Observable;\n\n var inbox = _signal2.default.Mailbox([]);\n var singleton = function singleton(action) {\n return [action];\n };\n var singletonMap = function singletonMap(signal) {\n return signal.map(singleton);\n };\n var address = _signal2.default.forwardTo(inbox.address, singleton);\n var modelWithEffect = config.init;\n\n function updateStep(_ref, action) {\n var _ref2 = _slicedToArray(_ref, 2);\n\n var oldModel = _ref2[0];\n var accumulatedEffects = _ref2[1];\n\n var _config$update = config.update(action, oldModel);\n\n var _config$update2 = _slicedToArray(_config$update, 2);\n\n var newModel = _config$update2[0];\n var additionalEffects = _config$update2[1];\n\n if (_ramda2.default.isNil(newModel)) throw new Error('Invalid model \\'' + newModel + '\\' returned by update function handling action \\'' + action.type + '\\'');\n if (_ramda2.default.isNil(additionalEffects)) throw new Error('Invalid effect \\'' + additionalEffects + '\\' returned by update function handling action \\'' + action.type + '\\'');\n var newEffects = accumulatedEffects.merge(additionalEffects);\n\n return [newModel, newEffects];\n }\n\n function update(actions, _ref3) {\n var _ref4 = _slicedToArray(_ref3, 1);\n\n var model = _ref4[0];\n\n return _ramda2.default.reduce(updateStep, [model, _effects2.default.none()], actions);\n }\n\n var listInputs = _ramda2.default.prepend(inbox.signal, _ramda2.default.map(singletonMap, config.inputs));\n var inputs = (_Rx$Observable = _rx2.default.Observable).merge.apply(_Rx$Observable, _toConsumableArray(listInputs));\n var effectsAndModel = inputs.scan(_ramda2.default.flip(update), config.init).shareReplay();\n\n var model = effectsAndModel.map(_ramda2.default.nth(0));\n\n var html = effectsAndModel.map(function (_ref5) {\n var _ref6 = _slicedToArray(_ref5, 1);\n\n var model = _ref6[0];\n return config.view(address, model);\n }).debounce(1, _rx2.default.Scheduler.RequestAnimationFrame);\n\n var tasks = effectsAndModel.flatMap(function (_ref7) {\n var _ref8 = _slicedToArray(_ref7, 2);\n\n var _ = _ref8[0];\n var effect = _ref8[1];\n return _effects2.default.toTask(address, effect);\n });\n\n return {\n model: model,\n html: html,\n tasks: tasks\n };\n}\n\n// type ConfSimple model action = { init : model\n// , update : (action, model) -> model\n// , view : {Address action, model} -> VirtualDOM }\n\n// AppSimple : ConfSimple model action -> App model action\nfunction AppSimple(config) {\n var inbox = _signal2.default.Mailbox(_data2.default.Nothing());\n var address = _signal2.default.forwardTo(inbox.address, _data2.default.Just);\n\n var inputs = inbox.signal;\n\n function update(maybeAction, model) {\n return maybeAction.map(function (action) {\n return config.update(action, model);\n }).getOrElse(model);\n }\n\n var model = inputs.scan(_ramda2.default.flip(update), config.init).shareReplay();\n var html = model.map(function (model) {\n return config.view(address, model);\n }).shareReplay();\n var tasks = _task2.default.empty();\n\n return {\n model: model,\n html: html,\n tasks: tasks\n };\n}\n\nexports.default = {\n App: App,\n AppSimple: AppSimple,\n runApp: runApp\n};\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/start-app.js\n ** module id = 1\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///./src/start-app.js?"); + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + eval("var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global, process) {// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.\n\n;(function (undefined) {\n\n var objectTypes = {\n 'function': true,\n 'object': true\n };\n\n function checkGlobal(value) {\n return (value && value.Object === Object) ? value : null;\n }\n\n var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;\n var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;\n var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);\n var freeSelf = checkGlobal(objectTypes[typeof self] && self);\n var freeWindow = checkGlobal(objectTypes[typeof window] && window);\n var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;\n var thisGlobal = checkGlobal(objectTypes[typeof this] && this);\n var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();\n\n var Rx = {\n internals: {},\n config: {\n Promise: root.Promise\n },\n helpers: { }\n };\n\n // Defaults\n var noop = Rx.helpers.noop = function () { },\n identity = Rx.helpers.identity = function (x) { return x; },\n defaultNow = Rx.helpers.defaultNow = Date.now,\n defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },\n defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },\n defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },\n defaultError = Rx.helpers.defaultError = function (err) { throw err; },\n isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },\n isFunction = Rx.helpers.isFunction = (function () {\n\n var isFn = function (value) {\n return typeof value == 'function' || false;\n };\n\n // fallback for older versions of Chrome and Safari\n if (isFn(/x/)) {\n isFn = function(value) {\n return typeof value == 'function' && toString.call(value) == '[object Function]';\n };\n }\n\n return isFn;\n }());\n\n function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}\n\n var errorObj = {e: {}};\n \n function tryCatcherGen(tryCatchTarget) {\n return function tryCatcher() {\n try {\n return tryCatchTarget.apply(this, arguments);\n } catch (e) {\n errorObj.e = e;\n return errorObj;\n }\n };\n }\n\n var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {\n if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }\n return tryCatcherGen(fn);\n };\n\n function thrower(e) {\n throw e;\n }\n\n Rx.config.longStackSupport = false;\n var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();\n hasStacks = !!stacks.e && !!stacks.e.stack;\n\n // All code after this point will be filtered from stack traces reported by RxJS\n var rStartingLine = captureLine(), rFileName;\n\n var STACK_JUMP_SEPARATOR = 'From previous event:';\n\n function makeStackTraceLong(error, observable) {\n // If possible, transform the error stack trace by removing Node and RxJS\n // cruft, then concatenating with the stack trace of `observable`.\n if (hasStacks &&\n observable.stack &&\n typeof error === 'object' &&\n error !== null &&\n error.stack &&\n error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1\n ) {\n var stacks = [];\n for (var o = observable; !!o; o = o.source) {\n if (o.stack) {\n stacks.unshift(o.stack);\n }\n }\n stacks.unshift(error.stack);\n\n var concatedStacks = stacks.join('\\n' + STACK_JUMP_SEPARATOR + '\\n');\n error.stack = filterStackString(concatedStacks);\n }\n }\n\n function filterStackString(stackString) {\n var lines = stackString.split('\\n'), desiredLines = [];\n for (var i = 0, len = lines.length; i < len; i++) {\n var line = lines[i];\n\n if (!isInternalFrame(line) && !isNodeFrame(line) && line) {\n desiredLines.push(line);\n }\n }\n return desiredLines.join('\\n');\n }\n\n function isInternalFrame(stackLine) {\n var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);\n if (!fileNameAndLineNumber) {\n return false;\n }\n var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];\n\n return fileName === rFileName &&\n lineNumber >= rStartingLine &&\n lineNumber <= rEndingLine;\n }\n\n function isNodeFrame(stackLine) {\n return stackLine.indexOf('(module.js:') !== -1 ||\n stackLine.indexOf('(node.js:') !== -1;\n }\n\n function captureLine() {\n if (!hasStacks) { return; }\n\n try {\n throw new Error();\n } catch (e) {\n var lines = e.stack.split('\\n');\n var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];\n var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);\n if (!fileNameAndLineNumber) { return; }\n\n rFileName = fileNameAndLineNumber[0];\n return fileNameAndLineNumber[1];\n }\n }\n\n function getFileNameAndLineNumber(stackLine) {\n // Named functions: 'at functionName (filename:lineNumber:columnNumber)'\n var attempt1 = /at .+ \\((.+):(\\d+):(?:\\d+)\\)$/.exec(stackLine);\n if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }\n\n // Anonymous functions: 'at filename:lineNumber:columnNumber'\n var attempt2 = /at ([^ ]+):(\\d+):(?:\\d+)$/.exec(stackLine);\n if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }\n\n // Firefox style: 'function@filename:lineNumber or @filename:lineNumber'\n var attempt3 = /.*@(.+):(\\d+)$/.exec(stackLine);\n if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }\n }\n\n var EmptyError = Rx.EmptyError = function() {\n this.message = 'Sequence contains no elements.';\n Error.call(this);\n };\n EmptyError.prototype = Object.create(Error.prototype);\n EmptyError.prototype.name = 'EmptyError';\n\n var ObjectDisposedError = Rx.ObjectDisposedError = function() {\n this.message = 'Object has been disposed';\n Error.call(this);\n };\n ObjectDisposedError.prototype = Object.create(Error.prototype);\n ObjectDisposedError.prototype.name = 'ObjectDisposedError';\n\n var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {\n this.message = 'Argument out of range';\n Error.call(this);\n };\n ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);\n ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';\n\n var NotSupportedError = Rx.NotSupportedError = function (message) {\n this.message = message || 'This operation is not supported';\n Error.call(this);\n };\n NotSupportedError.prototype = Object.create(Error.prototype);\n NotSupportedError.prototype.name = 'NotSupportedError';\n\n var NotImplementedError = Rx.NotImplementedError = function (message) {\n this.message = message || 'This operation is not implemented';\n Error.call(this);\n };\n NotImplementedError.prototype = Object.create(Error.prototype);\n NotImplementedError.prototype.name = 'NotImplementedError';\n\n var notImplemented = Rx.helpers.notImplemented = function () {\n throw new NotImplementedError();\n };\n\n var notSupported = Rx.helpers.notSupported = function () {\n throw new NotSupportedError();\n };\n\n // Shim in iterator support\n var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||\n '_es6shim_iterator_';\n // Bug for mozilla version\n if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {\n $iterator$ = '@@iterator';\n }\n\n var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };\n\n var isIterable = Rx.helpers.isIterable = function (o) {\n return o && o[$iterator$] !== undefined;\n };\n\n var isArrayLike = Rx.helpers.isArrayLike = function (o) {\n return o && o.length !== undefined;\n };\n\n Rx.helpers.iterator = $iterator$;\n\n var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {\n if (typeof thisArg === 'undefined') { return func; }\n switch(argCount) {\n case 0:\n return function() {\n return func.call(thisArg)\n };\n case 1:\n return function(arg) {\n return func.call(thisArg, arg);\n };\n case 2:\n return function(value, index) {\n return func.call(thisArg, value, index);\n };\n case 3:\n return function(value, index, collection) {\n return func.call(thisArg, value, index, collection);\n };\n }\n\n return function() {\n return func.apply(thisArg, arguments);\n };\n };\n\n /** Used to determine if values are of the language type Object */\n var dontEnums = ['toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'],\n dontEnumsLength = dontEnums.length;\n\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dateTag] = typedArrayTags[errorTag] =\ntypedArrayTags[funcTag] = typedArrayTags[mapTag] =\ntypedArrayTags[numberTag] = typedArrayTags[objectTag] =\ntypedArrayTags[regexpTag] = typedArrayTags[setTag] =\ntypedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;\n\nvar objectProto = Object.prototype,\n hasOwnProperty = objectProto.hasOwnProperty,\n objToString = objectProto.toString,\n MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;\n\nvar keys = Object.keys || (function() {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function(obj) {\n if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {\n throw new TypeError('Object.keys called on non-object');\n }\n\n var result = [], prop, i;\n\n for (prop in obj) {\n if (hasOwnProperty.call(obj, prop)) {\n result.push(prop);\n }\n }\n\n if (hasDontEnumBug) {\n for (i = 0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) {\n result.push(dontEnums[i]);\n }\n }\n }\n return result;\n };\n }());\n\nfunction equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {\n var objProps = keys(object),\n objLength = objProps.length,\n othProps = keys(other),\n othLength = othProps.length;\n\n if (objLength !== othLength && !isLoose) {\n return false;\n }\n var index = objLength, key;\n while (index--) {\n key = objProps[index];\n if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n var skipCtor = isLoose;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key],\n result;\n\n if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {\n return false;\n }\n skipCtor || (skipCtor = key === 'constructor');\n }\n if (!skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n if (objCtor !== othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor === 'function' && objCtor instanceof objCtor &&\n typeof othCtor === 'function' && othCtor instanceof othCtor)) {\n return false;\n }\n }\n return true;\n}\n\nfunction equalByTag(object, other, tag) {\n switch (tag) {\n case boolTag:\n case dateTag:\n return +object === +other;\n\n case errorTag:\n return object.name === other.name && object.message === other.message;\n\n case numberTag:\n return (object !== +object) ?\n other !== +other :\n object === +other;\n\n case regexpTag:\n case stringTag:\n return object === (other + '');\n }\n return false;\n}\n\nvar isObject = Rx.internals.isObject = function(value) {\n var type = typeof value;\n return !!value && (type === 'object' || type === 'function');\n};\n\nfunction isObjectLike(value) {\n return !!value && typeof value === 'object';\n}\n\nfunction isLength(value) {\n return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;\n}\n\nvar isHostObject = (function() {\n try {\n Object({ 'toString': 0 } + '');\n } catch(e) {\n return function() { return false; };\n }\n return function(value) {\n return typeof value.toString !== 'function' && typeof (value + '') === 'string';\n };\n}());\n\nfunction isTypedArray(value) {\n return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];\n}\n\nvar isArray = Array.isArray || function(value) {\n return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;\n};\n\nfunction arraySome (array, predicate) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nfunction equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {\n var index = -1,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {\n return false;\n }\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index],\n result;\n\n if (result !== undefined) {\n if (result) {\n continue;\n }\n return false;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (isLoose) {\n if (!arraySome(other, function(othValue) {\n return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);\n })) {\n return false;\n }\n } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {\n return false;\n }\n }\n return true;\n}\n\nfunction baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = arrayTag,\n othTag = arrayTag;\n\n if (!objIsArr) {\n objTag = objToString.call(object);\n if (objTag === argsTag) {\n objTag = objectTag;\n } else if (objTag !== objectTag) {\n objIsArr = isTypedArray(object);\n }\n }\n if (!othIsArr) {\n othTag = objToString.call(other);\n if (othTag === argsTag) {\n othTag = objectTag;\n }\n }\n var objIsObj = objTag === objectTag && !isHostObject(object),\n othIsObj = othTag === objectTag && !isHostObject(other),\n isSameTag = objTag === othTag;\n\n if (isSameTag && !(objIsArr || objIsObj)) {\n return equalByTag(object, other, objTag);\n }\n if (!isLoose) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);\n }\n }\n if (!isSameTag) {\n return false;\n }\n // Assume cyclic values are equal.\n // For more information on detecting circular references see https://es5.github.io/#JO.\n stackA || (stackA = []);\n stackB || (stackB = []);\n\n var length = stackA.length;\n while (length--) {\n if (stackA[length] === object) {\n return stackB[length] === other;\n }\n }\n // Add `object` and `other` to the stack of traversed objects.\n stackA.push(object);\n stackB.push(other);\n\n var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);\n\n stackA.pop();\n stackB.pop();\n\n return result;\n}\n\nfunction baseIsEqual(value, other, isLoose, stackA, stackB) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);\n}\n\nvar isEqual = Rx.internals.isEqual = function (value, other) {\n return baseIsEqual(value, other);\n};\n\n var hasProp = {}.hasOwnProperty,\n slice = Array.prototype.slice;\n\n var inherits = Rx.internals.inherits = function (child, parent) {\n function __() { this.constructor = child; }\n __.prototype = parent.prototype;\n child.prototype = new __();\n };\n\n var addProperties = Rx.internals.addProperties = function (obj) {\n for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }\n for (var idx = 0, ln = sources.length; idx < ln; idx++) {\n var source = sources[idx];\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n }\n };\n\n // Rx Utils\n var addRef = Rx.internals.addRef = function (xs, r) {\n return new AnonymousObservable(function (observer) {\n return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));\n });\n };\n\n function arrayInitialize(count, factory) {\n var a = new Array(count);\n for (var i = 0; i < count; i++) {\n a[i] = factory();\n }\n return a;\n }\n\n function IndexedItem(id, value) {\n this.id = id;\n this.value = value;\n }\n\n IndexedItem.prototype.compareTo = function (other) {\n var c = this.value.compareTo(other.value);\n c === 0 && (c = this.id - other.id);\n return c;\n };\n\n var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {\n this.items = new Array(capacity);\n this.length = 0;\n };\n\n var priorityProto = PriorityQueue.prototype;\n priorityProto.isHigherPriority = function (left, right) {\n return this.items[left].compareTo(this.items[right]) < 0;\n };\n\n priorityProto.percolate = function (index) {\n if (index >= this.length || index < 0) { return; }\n var parent = index - 1 >> 1;\n if (parent < 0 || parent === index) { return; }\n if (this.isHigherPriority(index, parent)) {\n var temp = this.items[index];\n this.items[index] = this.items[parent];\n this.items[parent] = temp;\n this.percolate(parent);\n }\n };\n\n priorityProto.heapify = function (index) {\n +index || (index = 0);\n if (index >= this.length || index < 0) { return; }\n var left = 2 * index + 1,\n right = 2 * index + 2,\n first = index;\n if (left < this.length && this.isHigherPriority(left, first)) {\n first = left;\n }\n if (right < this.length && this.isHigherPriority(right, first)) {\n first = right;\n }\n if (first !== index) {\n var temp = this.items[index];\n this.items[index] = this.items[first];\n this.items[first] = temp;\n this.heapify(first);\n }\n };\n\n priorityProto.peek = function () { return this.items[0].value; };\n\n priorityProto.removeAt = function (index) {\n this.items[index] = this.items[--this.length];\n this.items[this.length] = undefined;\n this.heapify();\n };\n\n priorityProto.dequeue = function () {\n var result = this.peek();\n this.removeAt(0);\n return result;\n };\n\n priorityProto.enqueue = function (item) {\n var index = this.length++;\n this.items[index] = new IndexedItem(PriorityQueue.count++, item);\n this.percolate(index);\n };\n\n priorityProto.remove = function (item) {\n for (var i = 0; i < this.length; i++) {\n if (this.items[i].value === item) {\n this.removeAt(i);\n return true;\n }\n }\n return false;\n };\n PriorityQueue.count = 0;\n\n /**\n * Represents a group of disposable resources that are disposed together.\n * @constructor\n */\n var CompositeDisposable = Rx.CompositeDisposable = function () {\n var args = [], i, len;\n if (Array.isArray(arguments[0])) {\n args = arguments[0];\n } else {\n len = arguments.length;\n args = new Array(len);\n for(i = 0; i < len; i++) { args[i] = arguments[i]; }\n }\n this.disposables = args;\n this.isDisposed = false;\n this.length = args.length;\n };\n\n var CompositeDisposablePrototype = CompositeDisposable.prototype;\n\n /**\n * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.\n * @param {Mixed} item Disposable to add.\n */\n CompositeDisposablePrototype.add = function (item) {\n if (this.isDisposed) {\n item.dispose();\n } else {\n this.disposables.push(item);\n this.length++;\n }\n };\n\n /**\n * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.\n * @param {Mixed} item Disposable to remove.\n * @returns {Boolean} true if found; false otherwise.\n */\n CompositeDisposablePrototype.remove = function (item) {\n var shouldDispose = false;\n if (!this.isDisposed) {\n var idx = this.disposables.indexOf(item);\n if (idx !== -1) {\n shouldDispose = true;\n this.disposables.splice(idx, 1);\n this.length--;\n item.dispose();\n }\n }\n return shouldDispose;\n };\n\n /**\n * Disposes all disposables in the group and removes them from the group.\n */\n CompositeDisposablePrototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n var len = this.disposables.length, currentDisposables = new Array(len);\n for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }\n this.disposables = [];\n this.length = 0;\n\n for (i = 0; i < len; i++) {\n currentDisposables[i].dispose();\n }\n }\n };\n\n /**\n * Provides a set of static methods for creating Disposables.\n * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.\n */\n var Disposable = Rx.Disposable = function (action) {\n this.isDisposed = false;\n this.action = action || noop;\n };\n\n /** Performs the task of cleaning up resources. */\n Disposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.action();\n this.isDisposed = true;\n }\n };\n\n /**\n * Creates a disposable object that invokes the specified action when disposed.\n * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.\n * @return {Disposable} The disposable object that runs the given action upon disposal.\n */\n var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };\n\n /**\n * Gets the disposable that does nothing when disposed.\n */\n var disposableEmpty = Disposable.empty = { dispose: noop };\n\n /**\n * Validates whether the given object is a disposable\n * @param {Object} Object to test whether it has a dispose method\n * @returns {Boolean} true if a disposable object, else false.\n */\n var isDisposable = Disposable.isDisposable = function (d) {\n return d && isFunction(d.dispose);\n };\n\n var checkDisposed = Disposable.checkDisposed = function (disposable) {\n if (disposable.isDisposed) { throw new ObjectDisposedError(); }\n };\n\n var disposableFixup = Disposable._fixup = function (result) {\n return isDisposable(result) ? result : disposableEmpty;\n };\n\n // Single assignment\n var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {\n this.isDisposed = false;\n this.current = null;\n };\n SingleAssignmentDisposable.prototype.getDisposable = function () {\n return this.current;\n };\n SingleAssignmentDisposable.prototype.setDisposable = function (value) {\n if (this.current) { throw new Error('Disposable has already been assigned'); }\n var shouldDispose = this.isDisposed;\n !shouldDispose && (this.current = value);\n shouldDispose && value && value.dispose();\n };\n SingleAssignmentDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n var old = this.current;\n this.current = null;\n old && old.dispose();\n }\n };\n\n // Multiple assignment disposable\n var SerialDisposable = Rx.SerialDisposable = function () {\n this.isDisposed = false;\n this.current = null;\n };\n SerialDisposable.prototype.getDisposable = function () {\n return this.current;\n };\n SerialDisposable.prototype.setDisposable = function (value) {\n var shouldDispose = this.isDisposed;\n if (!shouldDispose) {\n var old = this.current;\n this.current = value;\n }\n old && old.dispose();\n shouldDispose && value && value.dispose();\n };\n SerialDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n var old = this.current;\n this.current = null;\n }\n old && old.dispose();\n };\n\n var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {\n this._first = first;\n this._second = second;\n this.isDisposed = false;\n };\n\n BinaryDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n var old1 = this._first;\n this._first = null;\n old1 && old1.dispose();\n var old2 = this._second;\n this._second = null;\n old2 && old2.dispose();\n }\n };\n\n var NAryDisposable = Rx.NAryDisposable = function (disposables) {\n this._disposables = disposables;\n this.isDisposed = false;\n };\n\n NAryDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n for (var i = 0, len = this._disposables.length; i < len; i++) {\n this._disposables[i].dispose();\n }\n this._disposables.length = 0;\n }\n };\n\n /**\n * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.\n */\n var RefCountDisposable = Rx.RefCountDisposable = (function () {\n\n function InnerDisposable(disposable) {\n this.disposable = disposable;\n this.disposable.count++;\n this.isInnerDisposed = false;\n }\n\n InnerDisposable.prototype.dispose = function () {\n if (!this.disposable.isDisposed && !this.isInnerDisposed) {\n this.isInnerDisposed = true;\n this.disposable.count--;\n if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {\n this.disposable.isDisposed = true;\n this.disposable.underlyingDisposable.dispose();\n }\n }\n };\n\n /**\n * Initializes a new instance of the RefCountDisposable with the specified disposable.\n * @constructor\n * @param {Disposable} disposable Underlying disposable.\n */\n function RefCountDisposable(disposable) {\n this.underlyingDisposable = disposable;\n this.isDisposed = false;\n this.isPrimaryDisposed = false;\n this.count = 0;\n }\n\n /**\n * Disposes the underlying disposable only when all dependent disposables have been disposed\n */\n RefCountDisposable.prototype.dispose = function () {\n if (!this.isDisposed && !this.isPrimaryDisposed) {\n this.isPrimaryDisposed = true;\n if (this.count === 0) {\n this.isDisposed = true;\n this.underlyingDisposable.dispose();\n }\n }\n };\n\n /**\n * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.\n * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.\n */\n RefCountDisposable.prototype.getDisposable = function () {\n return this.isDisposed ? disposableEmpty : new InnerDisposable(this);\n };\n\n return RefCountDisposable;\n })();\n\n function ScheduledDisposable(scheduler, disposable) {\n this.scheduler = scheduler;\n this.disposable = disposable;\n this.isDisposed = false;\n }\n\n function scheduleItem(s, self) {\n if (!self.isDisposed) {\n self.isDisposed = true;\n self.disposable.dispose();\n }\n }\n\n ScheduledDisposable.prototype.dispose = function () {\n this.scheduler.schedule(this, scheduleItem);\n };\n\n var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {\n this.scheduler = scheduler;\n this.state = state;\n this.action = action;\n this.dueTime = dueTime;\n this.comparer = comparer || defaultSubComparer;\n this.disposable = new SingleAssignmentDisposable();\n };\n\n ScheduledItem.prototype.invoke = function () {\n this.disposable.setDisposable(this.invokeCore());\n };\n\n ScheduledItem.prototype.compareTo = function (other) {\n return this.comparer(this.dueTime, other.dueTime);\n };\n\n ScheduledItem.prototype.isCancelled = function () {\n return this.disposable.isDisposed;\n };\n\n ScheduledItem.prototype.invokeCore = function () {\n return disposableFixup(this.action(this.scheduler, this.state));\n };\n\n /** Provides a set of static properties to access commonly used schedulers. */\n var Scheduler = Rx.Scheduler = (function () {\n\n function Scheduler() { }\n\n /** Determines whether the given object is a scheduler */\n Scheduler.isScheduler = function (s) {\n return s instanceof Scheduler;\n };\n\n var schedulerProto = Scheduler.prototype;\n\n /**\n * Schedules an action to be executed.\n * @param state State passed to the action to be executed.\n * @param {Function} action Action to be executed.\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\n */\n schedulerProto.schedule = function (state, action) {\n throw new NotImplementedError();\n };\n\n /**\n * Schedules an action to be executed after dueTime.\n * @param state State passed to the action to be executed.\n * @param {Function} action Action to be executed.\n * @param {Number} dueTime Relative time after which to execute the action.\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\n */\n schedulerProto.scheduleFuture = function (state, dueTime, action) {\n var dt = dueTime;\n dt instanceof Date && (dt = dt - this.now());\n dt = Scheduler.normalize(dt);\n\n if (dt === 0) { return this.schedule(state, action); }\n\n return this._scheduleFuture(state, dt, action);\n };\n\n schedulerProto._scheduleFuture = function (state, dueTime, action) {\n throw new NotImplementedError();\n };\n\n /** Gets the current time according to the local machine's system clock. */\n Scheduler.now = defaultNow;\n\n /** Gets the current time according to the local machine's system clock. */\n Scheduler.prototype.now = defaultNow;\n\n /**\n * Normalizes the specified TimeSpan value to a positive value.\n * @param {Number} timeSpan The time span value to normalize.\n * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0\n */\n Scheduler.normalize = function (timeSpan) {\n timeSpan < 0 && (timeSpan = 0);\n return timeSpan;\n };\n\n return Scheduler;\n }());\n\n var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;\n\n (function (schedulerProto) {\n\n function invokeRecImmediate(scheduler, pair) {\n var state = pair[0], action = pair[1], group = new CompositeDisposable();\n action(state, innerAction);\n return group;\n\n function innerAction(state2) {\n var isAdded = false, isDone = false;\n\n var d = scheduler.schedule(state2, scheduleWork);\n if (!isDone) {\n group.add(d);\n isAdded = true;\n }\n\n function scheduleWork(_, state3) {\n if (isAdded) {\n group.remove(d);\n } else {\n isDone = true;\n }\n action(state3, innerAction);\n return disposableEmpty;\n }\n }\n }\n\n function invokeRecDate(scheduler, pair) {\n var state = pair[0], action = pair[1], group = new CompositeDisposable();\n action(state, innerAction);\n return group;\n\n function innerAction(state2, dueTime1) {\n var isAdded = false, isDone = false;\n\n var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);\n if (!isDone) {\n group.add(d);\n isAdded = true;\n }\n\n function scheduleWork(_, state3) {\n if (isAdded) {\n group.remove(d);\n } else {\n isDone = true;\n }\n action(state3, innerAction);\n return disposableEmpty;\n }\n }\n }\n\n /**\n * Schedules an action to be executed recursively.\n * @param {Mixed} state State passed to the action to be executed.\n * @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.\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\n */\n schedulerProto.scheduleRecursive = function (state, action) {\n return this.schedule([state, action], invokeRecImmediate);\n };\n\n /**\n * Schedules an action to be executed recursively after a specified relative or absolute due time.\n * @param {Mixed} state State passed to the action to be executed.\n * @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.\n * @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.\n * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).\n */\n schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {\n return this.scheduleFuture([state, action], dueTime, invokeRecDate);\n };\n\n }(Scheduler.prototype));\n\n (function (schedulerProto) {\n\n /**\n * 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.\n * @param {Mixed} state Initial state passed to the action upon the first iteration.\n * @param {Number} period Period for running the work periodically.\n * @param {Function} action Action to be executed, potentially updating the state.\n * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).\n */\n schedulerProto.schedulePeriodic = function(state, period, action) {\n if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }\n period = normalizeTime(period);\n var s = state, id = root.setInterval(function () { s = action(s); }, period);\n return disposableCreate(function () { root.clearInterval(id); });\n };\n\n }(Scheduler.prototype));\n\n (function (schedulerProto) {\n /**\n * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.\n * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.\n * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.\n */\n schedulerProto.catchError = schedulerProto['catch'] = function (handler) {\n return new CatchScheduler(this, handler);\n };\n }(Scheduler.prototype));\n\n var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {\n function createTick(self) {\n return function tick(command, recurse) {\n recurse(0, self._period);\n var state = tryCatch(self._action)(self._state);\n if (state === errorObj) {\n self._cancel.dispose();\n thrower(state.e);\n }\n self._state = state;\n };\n }\n\n function SchedulePeriodicRecursive(scheduler, state, period, action) {\n this._scheduler = scheduler;\n this._state = state;\n this._period = period;\n this._action = action;\n }\n\n SchedulePeriodicRecursive.prototype.start = function () {\n var d = new SingleAssignmentDisposable();\n this._cancel = d;\n d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));\n\n return d;\n };\n\n return SchedulePeriodicRecursive;\n }());\n\n /** Gets a scheduler that schedules work immediately on the current thread. */\n var ImmediateScheduler = (function (__super__) {\n inherits(ImmediateScheduler, __super__);\n function ImmediateScheduler() {\n __super__.call(this);\n }\n\n ImmediateScheduler.prototype.schedule = function (state, action) {\n return disposableFixup(action(this, state));\n };\n\n return ImmediateScheduler;\n }(Scheduler));\n\n var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();\n\n /**\n * Gets a scheduler that schedules work as soon as possible on the current thread.\n */\n var CurrentThreadScheduler = (function (__super__) {\n var queue;\n\n function runTrampoline () {\n while (queue.length > 0) {\n var item = queue.dequeue();\n !item.isCancelled() && item.invoke();\n }\n }\n\n inherits(CurrentThreadScheduler, __super__);\n function CurrentThreadScheduler() {\n __super__.call(this);\n }\n\n CurrentThreadScheduler.prototype.schedule = function (state, action) {\n var si = new ScheduledItem(this, state, action, this.now());\n\n if (!queue) {\n queue = new PriorityQueue(4);\n queue.enqueue(si);\n\n var result = tryCatch(runTrampoline)();\n queue = null;\n if (result === errorObj) { thrower(result.e); }\n } else {\n queue.enqueue(si);\n }\n return si.disposable;\n };\n\n CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };\n\n return CurrentThreadScheduler;\n }(Scheduler));\n\n var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();\n\n var scheduleMethod, clearMethod;\n\n var localTimer = (function () {\n var localSetTimeout, localClearTimeout = noop;\n if (!!root.setTimeout) {\n localSetTimeout = root.setTimeout;\n localClearTimeout = root.clearTimeout;\n } else if (!!root.WScript) {\n localSetTimeout = function (fn, time) {\n root.WScript.Sleep(time);\n fn();\n };\n } else {\n throw new NotSupportedError();\n }\n\n return {\n setTimeout: localSetTimeout,\n clearTimeout: localClearTimeout\n };\n }());\n var localSetTimeout = localTimer.setTimeout,\n localClearTimeout = localTimer.clearTimeout;\n\n (function () {\n\n var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;\n\n clearMethod = function (handle) {\n delete tasksByHandle[handle];\n };\n\n function runTask(handle) {\n if (currentlyRunning) {\n localSetTimeout(function () { runTask(handle); }, 0);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunning = true;\n var result = tryCatch(task)();\n clearMethod(handle);\n currentlyRunning = false;\n if (result === errorObj) { thrower(result.e); }\n }\n }\n }\n\n var reNative = new RegExp('^' +\n String(toString)\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/toString| for [^\\]]+/g, '.*?') + '$'\n );\n\n var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&\n !reNative.test(setImmediate) && setImmediate;\n\n function postMessageSupported () {\n // Ensure not in a worker\n if (!root.postMessage || root.importScripts) { return false; }\n var isAsync = false, oldHandler = root.onmessage;\n // Test for async\n root.onmessage = function () { isAsync = true; };\n root.postMessage('', '*');\n root.onmessage = oldHandler;\n\n return isAsync;\n }\n\n // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout\n if (isFunction(setImmediate)) {\n scheduleMethod = function (action) {\n var id = nextHandle++;\n tasksByHandle[id] = action;\n setImmediate(function () { runTask(id); });\n\n return id;\n };\n } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {\n scheduleMethod = function (action) {\n var id = nextHandle++;\n tasksByHandle[id] = action;\n process.nextTick(function () { runTask(id); });\n\n return id;\n };\n } else if (postMessageSupported()) {\n var MSG_PREFIX = 'ms.rx.schedule' + Math.random();\n\n var onGlobalPostMessage = function (event) {\n // Only if we're a match to avoid any other global events\n if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {\n runTask(event.data.substring(MSG_PREFIX.length));\n }\n };\n\n root.addEventListener('message', onGlobalPostMessage, false);\n\n scheduleMethod = function (action) {\n var id = nextHandle++;\n tasksByHandle[id] = action;\n root.postMessage(MSG_PREFIX + currentId, '*');\n return id;\n };\n } else if (!!root.MessageChannel) {\n var channel = new root.MessageChannel();\n\n channel.port1.onmessage = function (e) { runTask(e.data); };\n\n scheduleMethod = function (action) {\n var id = nextHandle++;\n tasksByHandle[id] = action;\n channel.port2.postMessage(id);\n return id;\n };\n } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {\n\n scheduleMethod = function (action) {\n var scriptElement = root.document.createElement('script');\n var id = nextHandle++;\n tasksByHandle[id] = action;\n\n scriptElement.onreadystatechange = function () {\n runTask(id);\n scriptElement.onreadystatechange = null;\n scriptElement.parentNode.removeChild(scriptElement);\n scriptElement = null;\n };\n root.document.documentElement.appendChild(scriptElement);\n return id;\n };\n\n } else {\n scheduleMethod = function (action) {\n var id = nextHandle++;\n tasksByHandle[id] = action;\n localSetTimeout(function () {\n runTask(id);\n }, 0);\n\n return id;\n };\n }\n }());\n\n /**\n * Gets a scheduler that schedules work via a timed callback based upon platform.\n */\n var DefaultScheduler = (function (__super__) {\n inherits(DefaultScheduler, __super__);\n function DefaultScheduler() {\n __super__.call(this);\n }\n\n function scheduleAction(disposable, action, scheduler, state) {\n return function schedule() {\n disposable.setDisposable(Disposable._fixup(action(scheduler, state)));\n };\n }\n\n function ClearDisposable(id) {\n this._id = id;\n this.isDisposed = false;\n }\n\n ClearDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n clearMethod(this._id);\n }\n };\n\n function LocalClearDisposable(id) {\n this._id = id;\n this.isDisposed = false;\n }\n\n LocalClearDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n localClearTimeout(this._id);\n }\n };\n\n DefaultScheduler.prototype.schedule = function (state, action) {\n var disposable = new SingleAssignmentDisposable(),\n id = scheduleMethod(scheduleAction(disposable, action, this, state));\n return new BinaryDisposable(disposable, new ClearDisposable(id));\n };\n\n DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {\n if (dueTime === 0) { return this.schedule(state, action); }\n var disposable = new SingleAssignmentDisposable(),\n id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);\n return new BinaryDisposable(disposable, new LocalClearDisposable(id));\n };\n\n return DefaultScheduler;\n }(Scheduler));\n\n var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();\n\n var CatchScheduler = (function (__super__) {\n inherits(CatchScheduler, __super__);\n\n function CatchScheduler(scheduler, handler) {\n this._scheduler = scheduler;\n this._handler = handler;\n this._recursiveOriginal = null;\n this._recursiveWrapper = null;\n __super__.call(this);\n }\n\n CatchScheduler.prototype.schedule = function (state, action) {\n return this._scheduler.schedule(state, this._wrap(action));\n };\n\n CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) {\n return this._scheduler.schedule(state, dueTime, this._wrap(action));\n };\n\n CatchScheduler.prototype.now = function () { return this._scheduler.now(); };\n\n CatchScheduler.prototype._clone = function (scheduler) {\n return new CatchScheduler(scheduler, this._handler);\n };\n\n CatchScheduler.prototype._wrap = function (action) {\n var parent = this;\n return function (self, state) {\n var res = tryCatch(action)(parent._getRecursiveWrapper(self), state);\n if (res === errorObj) {\n if (!parent._handler(res.e)) { thrower(res.e); }\n return disposableEmpty;\n }\n return disposableFixup(res);\n };\n };\n\n CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {\n if (this._recursiveOriginal !== scheduler) {\n this._recursiveOriginal = scheduler;\n var wrapper = this._clone(scheduler);\n wrapper._recursiveOriginal = scheduler;\n wrapper._recursiveWrapper = wrapper;\n this._recursiveWrapper = wrapper;\n }\n return this._recursiveWrapper;\n };\n\n CatchScheduler.prototype.schedulePeriodic = function (state, period, action) {\n var self = this, failed = false, d = new SingleAssignmentDisposable();\n\n d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) {\n if (failed) { return null; }\n var res = tryCatch(action)(state1);\n if (res === errorObj) {\n failed = true;\n if (!self._handler(res.e)) { thrower(res.e); }\n d.dispose();\n return null;\n }\n return res;\n }));\n\n return d;\n };\n\n return CatchScheduler;\n }(Scheduler));\n\n /**\n * Represents a notification to an observer.\n */\n var Notification = Rx.Notification = (function () {\n function Notification() {\n\n }\n\n Notification.prototype._accept = function (onNext, onError, onCompleted) {\n throw new NotImplementedError();\n };\n\n Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {\n throw new NotImplementedError();\n };\n\n /**\n * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.\n * @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..\n * @param {Function} onError Function to invoke for an OnError notification.\n * @param {Function} onCompleted Function to invoke for an OnCompleted notification.\n * @returns {Any} Result produced by the observation.\n */\n Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {\n return observerOrOnNext && typeof observerOrOnNext === 'object' ?\n this._acceptObserver(observerOrOnNext) :\n this._accept(observerOrOnNext, onError, onCompleted);\n };\n\n /**\n * Returns an observable sequence with a single notification.\n *\n * @memberOf Notifications\n * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.\n * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.\n */\n Notification.prototype.toObservable = function (scheduler) {\n var self = this;\n isScheduler(scheduler) || (scheduler = immediateScheduler);\n return new AnonymousObservable(function (o) {\n return scheduler.schedule(self, function (_, notification) {\n notification._acceptObserver(o);\n notification.kind === 'N' && o.onCompleted();\n });\n });\n };\n\n return Notification;\n })();\n\n var OnNextNotification = (function (__super__) {\n inherits(OnNextNotification, __super__);\n function OnNextNotification(value) {\n this.value = value;\n this.kind = 'N';\n }\n\n OnNextNotification.prototype._accept = function (onNext) {\n return onNext(this.value);\n };\n\n OnNextNotification.prototype._acceptObserver = function (o) {\n return o.onNext(this.value);\n };\n\n OnNextNotification.prototype.toString = function () {\n return 'OnNext(' + this.value + ')';\n };\n\n return OnNextNotification;\n }(Notification));\n\n var OnErrorNotification = (function (__super__) {\n inherits(OnErrorNotification, __super__);\n function OnErrorNotification(error) {\n this.error = error;\n this.kind = 'E';\n }\n\n OnErrorNotification.prototype._accept = function (onNext, onError) {\n return onError(this.error);\n };\n\n OnErrorNotification.prototype._acceptObserver = function (o) {\n return o.onError(this.error);\n };\n\n OnErrorNotification.prototype.toString = function () {\n return 'OnError(' + this.error + ')';\n };\n\n return OnErrorNotification;\n }(Notification));\n\n var OnCompletedNotification = (function (__super__) {\n inherits(OnCompletedNotification, __super__);\n function OnCompletedNotification() {\n this.kind = 'C';\n }\n\n OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {\n return onCompleted();\n };\n\n OnCompletedNotification.prototype._acceptObserver = function (o) {\n return o.onCompleted();\n };\n\n OnCompletedNotification.prototype.toString = function () {\n return 'OnCompleted()';\n };\n\n return OnCompletedNotification;\n }(Notification));\n\n /**\n * Creates an object that represents an OnNext notification to an observer.\n * @param {Any} value The value contained in the notification.\n * @returns {Notification} The OnNext notification containing the value.\n */\n var notificationCreateOnNext = Notification.createOnNext = function (value) {\n return new OnNextNotification(value);\n };\n\n /**\n * Creates an object that represents an OnError notification to an observer.\n * @param {Any} error The exception contained in the notification.\n * @returns {Notification} The OnError notification containing the exception.\n */\n var notificationCreateOnError = Notification.createOnError = function (error) {\n return new OnErrorNotification(error);\n };\n\n /**\n * Creates an object that represents an OnCompleted notification to an observer.\n * @returns {Notification} The OnCompleted notification.\n */\n var notificationCreateOnCompleted = Notification.createOnCompleted = function () {\n return new OnCompletedNotification();\n };\n\n /**\n * Supports push-style iteration over an observable sequence.\n */\n var Observer = Rx.Observer = function () { };\n\n /**\n * Creates a notification callback from an observer.\n * @returns The action that forwards its input notification to the underlying observer.\n */\n Observer.prototype.toNotifier = function () {\n var observer = this;\n return function (n) { return n.accept(observer); };\n };\n\n /**\n * Hides the identity of an observer.\n * @returns An observer that hides the identity of the specified observer.\n */\n Observer.prototype.asObserver = function () {\n var self = this;\n return new AnonymousObserver(\n function (x) { self.onNext(x); },\n function (err) { self.onError(err); },\n function () { self.onCompleted(); });\n };\n\n /**\n * 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.\n * If a violation is detected, an Error is thrown from the offending observer method call.\n * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.\n */\n Observer.prototype.checked = function () { return new CheckedObserver(this); };\n\n /**\n * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.\n * @param {Function} [onNext] Observer's OnNext action implementation.\n * @param {Function} [onError] Observer's OnError action implementation.\n * @param {Function} [onCompleted] Observer's OnCompleted action implementation.\n * @returns {Observer} The observer object implemented using the given actions.\n */\n var observerCreate = Observer.create = function (onNext, onError, onCompleted) {\n onNext || (onNext = noop);\n onError || (onError = defaultError);\n onCompleted || (onCompleted = noop);\n return new AnonymousObserver(onNext, onError, onCompleted);\n };\n\n /**\n * Creates an observer from a notification callback.\n * @param {Function} handler Action that handles a notification.\n * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.\n */\n Observer.fromNotifier = function (handler, thisArg) {\n var cb = bindCallback(handler, thisArg, 1);\n return new AnonymousObserver(function (x) {\n return cb(notificationCreateOnNext(x));\n }, function (e) {\n return cb(notificationCreateOnError(e));\n }, function () {\n return cb(notificationCreateOnCompleted());\n });\n };\n\n /**\n * Schedules the invocation of observer methods on the given scheduler.\n * @param {Scheduler} scheduler Scheduler to schedule observer messages on.\n * @returns {Observer} Observer whose messages are scheduled on the given scheduler.\n */\n Observer.prototype.notifyOn = function (scheduler) {\n return new ObserveOnObserver(scheduler, this);\n };\n\n Observer.prototype.makeSafe = function(disposable) {\n return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);\n };\n\n /**\n * Abstract base class for implementations of the Observer class.\n * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.\n */\n var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {\n inherits(AbstractObserver, __super__);\n\n /**\n * Creates a new observer in a non-stopped state.\n */\n function AbstractObserver() {\n this.isStopped = false;\n }\n\n // Must be implemented by other observers\n AbstractObserver.prototype.next = notImplemented;\n AbstractObserver.prototype.error = notImplemented;\n AbstractObserver.prototype.completed = notImplemented;\n\n /**\n * Notifies the observer of a new element in the sequence.\n * @param {Any} value Next element in the sequence.\n */\n AbstractObserver.prototype.onNext = function (value) {\n !this.isStopped && this.next(value);\n };\n\n /**\n * Notifies the observer that an exception has occurred.\n * @param {Any} error The error that has occurred.\n */\n AbstractObserver.prototype.onError = function (error) {\n if (!this.isStopped) {\n this.isStopped = true;\n this.error(error);\n }\n };\n\n /**\n * Notifies the observer of the end of the sequence.\n */\n AbstractObserver.prototype.onCompleted = function () {\n if (!this.isStopped) {\n this.isStopped = true;\n this.completed();\n }\n };\n\n /**\n * Disposes the observer, causing it to transition to the stopped state.\n */\n AbstractObserver.prototype.dispose = function () { this.isStopped = true; };\n\n AbstractObserver.prototype.fail = function (e) {\n if (!this.isStopped) {\n this.isStopped = true;\n this.error(e);\n return true;\n }\n\n return false;\n };\n\n return AbstractObserver;\n }(Observer));\n\n /**\n * Class to create an Observer instance from delegate-based implementations of the on* methods.\n */\n var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {\n inherits(AnonymousObserver, __super__);\n\n /**\n * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.\n * @param {Any} onNext Observer's OnNext action implementation.\n * @param {Any} onError Observer's OnError action implementation.\n * @param {Any} onCompleted Observer's OnCompleted action implementation.\n */\n function AnonymousObserver(onNext, onError, onCompleted) {\n __super__.call(this);\n this._onNext = onNext;\n this._onError = onError;\n this._onCompleted = onCompleted;\n }\n\n /**\n * Calls the onNext action.\n * @param {Any} value Next element in the sequence.\n */\n AnonymousObserver.prototype.next = function (value) {\n this._onNext(value);\n };\n\n /**\n * Calls the onError action.\n * @param {Any} error The error that has occurred.\n */\n AnonymousObserver.prototype.error = function (error) {\n this._onError(error);\n };\n\n /**\n * Calls the onCompleted action.\n */\n AnonymousObserver.prototype.completed = function () {\n this._onCompleted();\n };\n\n return AnonymousObserver;\n }(AbstractObserver));\n\n var CheckedObserver = (function (__super__) {\n inherits(CheckedObserver, __super__);\n\n function CheckedObserver(observer) {\n __super__.call(this);\n this._observer = observer;\n this._state = 0; // 0 - idle, 1 - busy, 2 - done\n }\n\n var CheckedObserverPrototype = CheckedObserver.prototype;\n\n CheckedObserverPrototype.onNext = function (value) {\n this.checkAccess();\n var res = tryCatch(this._observer.onNext).call(this._observer, value);\n this._state = 0;\n res === errorObj && thrower(res.e);\n };\n\n CheckedObserverPrototype.onError = function (err) {\n this.checkAccess();\n var res = tryCatch(this._observer.onError).call(this._observer, err);\n this._state = 2;\n res === errorObj && thrower(res.e);\n };\n\n CheckedObserverPrototype.onCompleted = function () {\n this.checkAccess();\n var res = tryCatch(this._observer.onCompleted).call(this._observer);\n this._state = 2;\n res === errorObj && thrower(res.e);\n };\n\n CheckedObserverPrototype.checkAccess = function () {\n if (this._state === 1) { throw new Error('Re-entrancy detected'); }\n if (this._state === 2) { throw new Error('Observer completed'); }\n if (this._state === 0) { this._state = 1; }\n };\n\n return CheckedObserver;\n }(Observer));\n\n var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {\n inherits(ScheduledObserver, __super__);\n\n function ScheduledObserver(scheduler, observer) {\n __super__.call(this);\n this.scheduler = scheduler;\n this.observer = observer;\n this.isAcquired = false;\n this.hasFaulted = false;\n this.queue = [];\n this.disposable = new SerialDisposable();\n }\n\n function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }\n function enqueueError(observer, e) { return function () { observer.onError(e); }; }\n function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }\n\n ScheduledObserver.prototype.next = function (x) {\n this.queue.push(enqueueNext(this.observer, x));\n };\n\n ScheduledObserver.prototype.error = function (e) {\n this.queue.push(enqueueError(this.observer, e));\n };\n\n ScheduledObserver.prototype.completed = function () {\n this.queue.push(enqueueCompleted(this.observer));\n };\n\n\n function scheduleMethod(state, recurse) {\n var work;\n if (state.queue.length > 0) {\n work = state.queue.shift();\n } else {\n state.isAcquired = false;\n return;\n }\n var res = tryCatch(work)();\n if (res === errorObj) {\n state.queue = [];\n state.hasFaulted = true;\n return thrower(res.e);\n }\n recurse(state);\n }\n\n ScheduledObserver.prototype.ensureActive = function () {\n var isOwner = false;\n if (!this.hasFaulted && this.queue.length > 0) {\n isOwner = !this.isAcquired;\n this.isAcquired = true;\n }\n isOwner &&\n this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));\n };\n\n ScheduledObserver.prototype.dispose = function () {\n __super__.prototype.dispose.call(this);\n this.disposable.dispose();\n };\n\n return ScheduledObserver;\n }(AbstractObserver));\n\n var ObserveOnObserver = (function (__super__) {\n inherits(ObserveOnObserver, __super__);\n\n function ObserveOnObserver(scheduler, observer, cancel) {\n __super__.call(this, scheduler, observer);\n this._cancel = cancel;\n }\n\n ObserveOnObserver.prototype.next = function (value) {\n __super__.prototype.next.call(this, value);\n this.ensureActive();\n };\n\n ObserveOnObserver.prototype.error = function (e) {\n __super__.prototype.error.call(this, e);\n this.ensureActive();\n };\n\n ObserveOnObserver.prototype.completed = function () {\n __super__.prototype.completed.call(this);\n this.ensureActive();\n };\n\n ObserveOnObserver.prototype.dispose = function () {\n __super__.prototype.dispose.call(this);\n this._cancel && this._cancel.dispose();\n this._cancel = null;\n };\n\n return ObserveOnObserver;\n })(ScheduledObserver);\n\n var observableProto;\n\n /**\n * Represents a push-style collection.\n */\n var Observable = Rx.Observable = (function () {\n\n function makeSubscribe(self, subscribe) {\n return function (o) {\n var oldOnError = o.onError;\n o.onError = function (e) {\n makeStackTraceLong(e, self);\n oldOnError.call(o, e);\n };\n\n return subscribe.call(self, o);\n };\n }\n\n function Observable() {\n if (Rx.config.longStackSupport && hasStacks) {\n var oldSubscribe = this._subscribe;\n var e = tryCatch(thrower)(new Error()).e;\n this.stack = e.stack.substring(e.stack.indexOf('\\n') + 1);\n this._subscribe = makeSubscribe(this, oldSubscribe);\n }\n }\n\n observableProto = Observable.prototype;\n\n /**\n * Determines whether the given object is an Observable\n * @param {Any} An object to determine whether it is an Observable\n * @returns {Boolean} true if an Observable, else false.\n */\n Observable.isObservable = function (o) {\n return o && isFunction(o.subscribe);\n };\n\n /**\n * Subscribes an o to the observable sequence.\n * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.\n * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.\n * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.\n * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.\n */\n observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {\n return this._subscribe(typeof oOrOnNext === 'object' ?\n oOrOnNext :\n observerCreate(oOrOnNext, onError, onCompleted));\n };\n\n /**\n * Subscribes to the next value in the sequence with an optional \"this\" argument.\n * @param {Function} onNext The function to invoke on each element in the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.\n */\n observableProto.subscribeOnNext = function (onNext, thisArg) {\n return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));\n };\n\n /**\n * Subscribes to an exceptional condition in the sequence with an optional \"this\" argument.\n * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.\n */\n observableProto.subscribeOnError = function (onError, thisArg) {\n return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));\n };\n\n /**\n * Subscribes to the next value in the sequence with an optional \"this\" argument.\n * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.\n */\n observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {\n return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));\n };\n\n return Observable;\n })();\n\n var ObservableBase = Rx.ObservableBase = (function (__super__) {\n inherits(ObservableBase, __super__);\n\n function fixSubscriber(subscriber) {\n return subscriber && isFunction(subscriber.dispose) ? subscriber :\n isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;\n }\n\n function setDisposable(s, state) {\n var ado = state[0], self = state[1];\n var sub = tryCatch(self.subscribeCore).call(self, ado);\n if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }\n ado.setDisposable(fixSubscriber(sub));\n }\n\n function ObservableBase() {\n __super__.call(this);\n }\n\n ObservableBase.prototype._subscribe = function (o) {\n var ado = new AutoDetachObserver(o), state = [ado, this];\n\n if (currentThreadScheduler.scheduleRequired()) {\n currentThreadScheduler.schedule(state, setDisposable);\n } else {\n setDisposable(null, state);\n }\n return ado;\n };\n\n ObservableBase.prototype.subscribeCore = notImplemented;\n\n return ObservableBase;\n }(Observable));\n\nvar FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {\n\n inherits(FlatMapObservable, __super__);\n\n function FlatMapObservable(source, selector, resultSelector, thisArg) {\n this.resultSelector = isFunction(resultSelector) ? resultSelector : null;\n this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);\n this.source = source;\n __super__.call(this);\n }\n\n FlatMapObservable.prototype.subscribeCore = function(o) {\n return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(observer, selector, resultSelector, source) {\n this.i = 0;\n this.selector = selector;\n this.resultSelector = resultSelector;\n this.source = source;\n this.o = observer;\n AbstractObserver.call(this);\n }\n\n InnerObserver.prototype._wrapResult = function(result, x, i) {\n return this.resultSelector ?\n result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :\n result;\n };\n\n InnerObserver.prototype.next = function(x) {\n var i = this.i++;\n var result = tryCatch(this.selector)(x, i, this.source);\n if (result === errorObj) { return this.o.onError(result.e); }\n\n isPromise(result) && (result = observableFromPromise(result));\n (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));\n this.o.onNext(this._wrapResult(result, x, i));\n };\n\n InnerObserver.prototype.error = function(e) { this.o.onError(e); };\n\n InnerObserver.prototype.completed = function() { this.o.onCompleted(); };\n\n return FlatMapObservable;\n\n}(ObservableBase));\n\n var Enumerable = Rx.internals.Enumerable = function () { };\n\n function IsDisposedDisposable(state) {\n this._s = state;\n this.isDisposed = false;\n }\n\n IsDisposedDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this.isDisposed = true;\n this._s.isDisposed = true;\n }\n };\n\n var ConcatEnumerableObservable = (function(__super__) {\n inherits(ConcatEnumerableObservable, __super__);\n function ConcatEnumerableObservable(sources) {\n this.sources = sources;\n __super__.call(this);\n }\n\n function scheduleMethod(state, recurse) {\n if (state.isDisposed) { return; }\n var currentItem = tryCatch(state.e.next).call(state.e);\n if (currentItem === errorObj) { return state.o.onError(currentItem.e); }\n if (currentItem.done) { return state.o.onCompleted(); }\n\n // Check if promise\n var currentValue = currentItem.value;\n isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));\n\n var d = new SingleAssignmentDisposable();\n state.subscription.setDisposable(d);\n d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));\n }\n\n ConcatEnumerableObservable.prototype.subscribeCore = function (o) {\n var subscription = new SerialDisposable();\n var state = {\n isDisposed: false,\n o: o,\n subscription: subscription,\n e: this.sources[$iterator$]()\n };\n\n var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);\n return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);\n };\n\n function InnerObserver(state, recurse) {\n this._state = state;\n this._recurse = recurse;\n AbstractObserver.call(this);\n }\n\n inherits(InnerObserver, AbstractObserver);\n\n InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };\n InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };\n InnerObserver.prototype.completed = function () { this._recurse(this._state); };\n\n return ConcatEnumerableObservable;\n }(ObservableBase));\n\n Enumerable.prototype.concat = function () {\n return new ConcatEnumerableObservable(this);\n };\n\n var CatchErrorObservable = (function(__super__) {\n function CatchErrorObservable(sources) {\n this.sources = sources;\n __super__.call(this);\n }\n\n inherits(CatchErrorObservable, __super__);\n\n function scheduleMethod(state, recurse) {\n if (state.isDisposed) { return; }\n var currentItem = tryCatch(state.e.next).call(state.e);\n if (currentItem === errorObj) { return state.o.onError(currentItem.e); }\n if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }\n\n var currentValue = currentItem.value;\n isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));\n\n var d = new SingleAssignmentDisposable();\n state.subscription.setDisposable(d);\n d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));\n }\n\n CatchErrorObservable.prototype.subscribeCore = function (o) {\n var subscription = new SerialDisposable();\n var state = {\n isDisposed: false,\n e: this.sources[$iterator$](),\n subscription: subscription,\n lastError: null,\n o: o\n };\n\n var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);\n return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);\n };\n\n function InnerObserver(state, recurse) {\n this._state = state;\n this._recurse = recurse;\n AbstractObserver.call(this);\n }\n\n inherits(InnerObserver, AbstractObserver);\n\n InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };\n InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };\n InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };\n\n return CatchErrorObservable;\n }(ObservableBase));\n\n Enumerable.prototype.catchError = function () {\n return new CatchErrorObservable(this);\n };\n\n Enumerable.prototype.catchErrorWhen = function (notificationHandler) {\n var sources = this;\n return new AnonymousObservable(function (o) {\n var exceptions = new Subject(),\n notifier = new Subject(),\n handled = notificationHandler(exceptions),\n notificationDisposable = handled.subscribe(notifier);\n\n var e = sources[$iterator$]();\n\n var state = { isDisposed: false },\n lastError,\n subscription = new SerialDisposable();\n var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, self) {\n if (state.isDisposed) { return; }\n var currentItem = tryCatch(e.next).call(e);\n if (currentItem === errorObj) { return o.onError(currentItem.e); }\n\n if (currentItem.done) {\n if (lastError) {\n o.onError(lastError);\n } else {\n o.onCompleted();\n }\n return;\n }\n\n // Check if promise\n var currentValue = currentItem.value;\n isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));\n\n var outer = new SingleAssignmentDisposable();\n var inner = new SingleAssignmentDisposable();\n subscription.setDisposable(new BinaryDisposable(inner, outer));\n outer.setDisposable(currentValue.subscribe(\n function(x) { o.onNext(x); },\n function (exn) {\n inner.setDisposable(notifier.subscribe(self, function(ex) {\n o.onError(ex);\n }, function() {\n o.onCompleted();\n }));\n\n exceptions.onNext(exn);\n },\n function() { o.onCompleted(); }));\n });\n\n return new NAryDisposable([notificationDisposable, subscription, cancelable, new IsDisposedDisposable(state)]);\n });\n };\n\n var RepeatEnumerable = (function (__super__) {\n inherits(RepeatEnumerable, __super__);\n function RepeatEnumerable(v, c) {\n this.v = v;\n this.c = c == null ? -1 : c;\n }\n\n RepeatEnumerable.prototype[$iterator$] = function () {\n return new RepeatEnumerator(this);\n };\n\n function RepeatEnumerator(p) {\n this.v = p.v;\n this.l = p.c;\n }\n\n RepeatEnumerator.prototype.next = function () {\n if (this.l === 0) { return doneEnumerator; }\n if (this.l > 0) { this.l--; }\n return { done: false, value: this.v };\n };\n\n return RepeatEnumerable;\n }(Enumerable));\n\n var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {\n return new RepeatEnumerable(value, repeatCount);\n };\n\n var OfEnumerable = (function(__super__) {\n inherits(OfEnumerable, __super__);\n function OfEnumerable(s, fn, thisArg) {\n this.s = s;\n this.fn = fn ? bindCallback(fn, thisArg, 3) : null;\n }\n OfEnumerable.prototype[$iterator$] = function () {\n return new OfEnumerator(this);\n };\n\n function OfEnumerator(p) {\n this.i = -1;\n this.s = p.s;\n this.l = this.s.length;\n this.fn = p.fn;\n }\n\n OfEnumerator.prototype.next = function () {\n return ++this.i < this.l ?\n { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :\n doneEnumerator;\n };\n\n return OfEnumerable;\n }(Enumerable));\n\n var enumerableOf = Enumerable.of = function (source, selector, thisArg) {\n return new OfEnumerable(source, selector, thisArg);\n };\n\nvar ObserveOnObservable = (function (__super__) {\n inherits(ObserveOnObservable, __super__);\n function ObserveOnObservable(source, s) {\n this.source = source;\n this._s = s;\n __super__.call(this);\n }\n\n ObserveOnObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new ObserveOnObserver(this._s, o));\n };\n\n return ObserveOnObservable;\n}(ObservableBase));\n\n /**\n * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.\n *\n * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects\n * that require to be run on a scheduler, use subscribeOn.\n *\n * @param {Scheduler} scheduler Scheduler to notify observers on.\n * @returns {Observable} The source sequence whose observations happen on the specified scheduler.\n */\n observableProto.observeOn = function (scheduler) {\n return new ObserveOnObservable(this, scheduler);\n };\n\n var SubscribeOnObservable = (function (__super__) {\n inherits(SubscribeOnObservable, __super__);\n function SubscribeOnObservable(source, s) {\n this.source = source;\n this._s = s;\n __super__.call(this);\n }\n\n function scheduleMethod(scheduler, state) {\n var source = state[0], d = state[1], o = state[2];\n d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));\n }\n\n SubscribeOnObservable.prototype.subscribeCore = function (o) {\n var m = new SingleAssignmentDisposable(), d = new SerialDisposable();\n d.setDisposable(m);\n m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));\n return d;\n };\n\n return SubscribeOnObservable;\n }(ObservableBase));\n\n /**\n * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;\n * see the remarks section for more information on the distinction between subscribeOn and observeOn.\n\n * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer\n * callbacks on a scheduler, use observeOn.\n\n * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.\n * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.\n */\n observableProto.subscribeOn = function (scheduler) {\n return new SubscribeOnObservable(this, scheduler);\n };\n\n var FromPromiseObservable = (function(__super__) {\n inherits(FromPromiseObservable, __super__);\n function FromPromiseObservable(p, s) {\n this._p = p;\n this._s = s;\n __super__.call(this);\n }\n\n function scheduleNext(s, state) {\n var o = state[0], data = state[1];\n o.onNext(data);\n o.onCompleted();\n }\n\n function scheduleError(s, state) {\n var o = state[0], err = state[1];\n o.onError(err);\n }\n\n FromPromiseObservable.prototype.subscribeCore = function(o) {\n var sad = new SingleAssignmentDisposable(), self = this;\n\n this._p\n .then(function (data) {\n sad.setDisposable(self._s.schedule([o, data], scheduleNext));\n }, function (err) {\n sad.setDisposable(self._s.schedule([o, err], scheduleError));\n });\n\n return sad;\n };\n\n return FromPromiseObservable;\n }(ObservableBase));\n\n /**\n * Converts a Promise to an Observable sequence\n * @param {Promise} An ES6 Compliant promise.\n * @returns {Observable} An Observable sequence which wraps the existing promise success and failure.\n */\n var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {\n scheduler || (scheduler = defaultScheduler);\n return new FromPromiseObservable(promise, scheduler);\n };\n\n /*\n * Converts an existing observable sequence to an ES6 Compatible Promise\n * @example\n * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);\n *\n * // With config\n * Rx.config.Promise = RSVP.Promise;\n * var promise = Rx.Observable.return(42).toPromise();\n * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.\n * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.\n */\n observableProto.toPromise = function (promiseCtor) {\n promiseCtor || (promiseCtor = Rx.config.Promise);\n if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }\n var source = this;\n return new promiseCtor(function (resolve, reject) {\n // No cancellation can be done\n var value;\n source.subscribe(function (v) {\n value = v;\n }, reject, function () {\n resolve(value);\n });\n });\n };\n\n var ToArrayObservable = (function(__super__) {\n inherits(ToArrayObservable, __super__);\n function ToArrayObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n ToArrayObservable.prototype.subscribeCore = function(o) {\n return this.source.subscribe(new InnerObserver(o));\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(o) {\n this.o = o;\n this.a = [];\n AbstractObserver.call(this);\n }\n \n InnerObserver.prototype.next = function (x) { this.a.push(x); };\n InnerObserver.prototype.error = function (e) { this.o.onError(e); };\n InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };\n\n return ToArrayObservable;\n }(ObservableBase));\n\n /**\n * Creates an array from an observable sequence.\n * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.\n */\n observableProto.toArray = function () {\n return new ToArrayObservable(this);\n };\n\n /**\n * Creates an observable sequence from a specified subscribe method implementation.\n * @example\n * var res = Rx.Observable.create(function (observer) { return function () { } );\n * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );\n * var res = Rx.Observable.create(function (observer) { } );\n * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.\n * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.\n */\n Observable.create = function (subscribe, parent) {\n return new AnonymousObservable(subscribe, parent);\n };\n\n var Defer = (function(__super__) {\n inherits(Defer, __super__);\n function Defer(factory) {\n this._f = factory;\n __super__.call(this);\n }\n\n Defer.prototype.subscribeCore = function (o) {\n var result = tryCatch(this._f)();\n if (result === errorObj) { return observableThrow(result.e).subscribe(o);}\n isPromise(result) && (result = observableFromPromise(result));\n return result.subscribe(o);\n };\n\n return Defer;\n }(ObservableBase));\n\n /**\n * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.\n *\n * @example\n * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });\n * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.\n * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.\n */\n var observableDefer = Observable.defer = function (observableFactory) {\n return new Defer(observableFactory);\n };\n\n var EmptyObservable = (function(__super__) {\n inherits(EmptyObservable, __super__);\n function EmptyObservable(scheduler) {\n this.scheduler = scheduler;\n __super__.call(this);\n }\n\n EmptyObservable.prototype.subscribeCore = function (observer) {\n var sink = new EmptySink(observer, this.scheduler);\n return sink.run();\n };\n\n function EmptySink(observer, scheduler) {\n this.observer = observer;\n this.scheduler = scheduler;\n }\n\n function scheduleItem(s, state) {\n state.onCompleted();\n return disposableEmpty;\n }\n\n EmptySink.prototype.run = function () {\n var state = this.observer;\n return this.scheduler === immediateScheduler ?\n scheduleItem(null, state) :\n this.scheduler.schedule(state, scheduleItem);\n };\n\n return EmptyObservable;\n }(ObservableBase));\n\n var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);\n\n /**\n * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.\n *\n * @example\n * var res = Rx.Observable.empty();\n * var res = Rx.Observable.empty(Rx.Scheduler.timeout);\n * @param {Scheduler} [scheduler] Scheduler to send the termination call on.\n * @returns {Observable} An observable sequence with no elements.\n */\n var observableEmpty = Observable.empty = function (scheduler) {\n isScheduler(scheduler) || (scheduler = immediateScheduler);\n return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);\n };\n\n var FromObservable = (function(__super__) {\n inherits(FromObservable, __super__);\n function FromObservable(iterable, fn, scheduler) {\n this._iterable = iterable;\n this._fn = fn;\n this._scheduler = scheduler;\n __super__.call(this);\n }\n\n function createScheduleMethod(o, it, fn) {\n return function loopRecursive(i, recurse) {\n var next = tryCatch(it.next).call(it);\n if (next === errorObj) { return o.onError(next.e); }\n if (next.done) { return o.onCompleted(); }\n\n var result = next.value;\n\n if (isFunction(fn)) {\n result = tryCatch(fn)(result, i);\n if (result === errorObj) { return o.onError(result.e); }\n }\n\n o.onNext(result);\n recurse(i + 1);\n };\n }\n\n FromObservable.prototype.subscribeCore = function (o) {\n var list = Object(this._iterable),\n it = getIterable(list);\n\n return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));\n };\n\n return FromObservable;\n }(ObservableBase));\n\n var maxSafeInteger = Math.pow(2, 53) - 1;\n\n function StringIterable(s) {\n this._s = s;\n }\n\n StringIterable.prototype[$iterator$] = function () {\n return new StringIterator(this._s);\n };\n\n function StringIterator(s) {\n this._s = s;\n this._l = s.length;\n this._i = 0;\n }\n\n StringIterator.prototype[$iterator$] = function () {\n return this;\n };\n\n StringIterator.prototype.next = function () {\n return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;\n };\n\n function ArrayIterable(a) {\n this._a = a;\n }\n\n ArrayIterable.prototype[$iterator$] = function () {\n return new ArrayIterator(this._a);\n };\n\n function ArrayIterator(a) {\n this._a = a;\n this._l = toLength(a);\n this._i = 0;\n }\n\n ArrayIterator.prototype[$iterator$] = function () {\n return this;\n };\n\n ArrayIterator.prototype.next = function () {\n return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;\n };\n\n function numberIsFinite(value) {\n return typeof value === 'number' && root.isFinite(value);\n }\n\n function isNan(n) {\n return n !== n;\n }\n\n function getIterable(o) {\n var i = o[$iterator$], it;\n if (!i && typeof o === 'string') {\n it = new StringIterable(o);\n return it[$iterator$]();\n }\n if (!i && o.length !== undefined) {\n it = new ArrayIterable(o);\n return it[$iterator$]();\n }\n if (!i) { throw new TypeError('Object is not iterable'); }\n return o[$iterator$]();\n }\n\n function sign(value) {\n var number = +value;\n if (number === 0) { return number; }\n if (isNaN(number)) { return number; }\n return number < 0 ? -1 : 1;\n }\n\n function toLength(o) {\n var len = +o.length;\n if (isNaN(len)) { return 0; }\n if (len === 0 || !numberIsFinite(len)) { return len; }\n len = sign(len) * Math.floor(Math.abs(len));\n if (len <= 0) { return 0; }\n if (len > maxSafeInteger) { return maxSafeInteger; }\n return len;\n }\n\n /**\n * This method creates a new Observable sequence from an array-like or iterable object.\n * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.\n * @param {Function} [mapFn] Map function to call on every element of the array.\n * @param {Any} [thisArg] The context to use calling the mapFn if provided.\n * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.\n */\n var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {\n if (iterable == null) {\n throw new Error('iterable cannot be null.')\n }\n if (mapFn && !isFunction(mapFn)) {\n throw new Error('mapFn when provided must be a function');\n }\n if (mapFn) {\n var mapper = bindCallback(mapFn, thisArg, 2);\n }\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new FromObservable(iterable, mapper, scheduler);\n }\n\n var FromArrayObservable = (function(__super__) {\n inherits(FromArrayObservable, __super__);\n function FromArrayObservable(args, scheduler) {\n this._args = args;\n this._scheduler = scheduler;\n __super__.call(this);\n }\n\n function scheduleMethod(o, args) {\n var len = args.length;\n return function loopRecursive (i, recurse) {\n if (i < len) {\n o.onNext(args[i]);\n recurse(i + 1);\n } else {\n o.onCompleted();\n }\n };\n }\n\n FromArrayObservable.prototype.subscribeCore = function (o) {\n return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));\n };\n\n return FromArrayObservable;\n }(ObservableBase));\n\n /**\n * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.\n * @deprecated use Observable.from or Observable.of\n * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.\n * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.\n */\n var observableFromArray = Observable.fromArray = function (array, scheduler) {\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new FromArrayObservable(array, scheduler)\n };\n\n var GenerateObservable = (function (__super__) {\n inherits(GenerateObservable, __super__);\n function GenerateObservable(state, cndFn, itrFn, resFn, s) {\n this._state = state;\n this._cndFn = cndFn;\n this._itrFn = itrFn;\n this._resFn = resFn;\n this._s = s;\n this._first = true;\n __super__.call(this);\n }\n\n function scheduleRecursive(self, recurse) {\n if (self._first) {\n self._first = false;\n } else {\n self._state = tryCatch(self._itrFn)(self._state);\n if (self._state === errorObj) { return self._o.onError(self._state.e); }\n }\n var hasResult = tryCatch(self._cndFn)(self._state);\n if (hasResult === errorObj) { return self._o.onError(hasResult.e); }\n if (hasResult) {\n var result = tryCatch(self._resFn)(self._state);\n if (result === errorObj) { return self._o.onError(result.e); }\n self._o.onNext(result);\n recurse(self);\n } else {\n self._o.onCompleted();\n }\n }\n\n GenerateObservable.prototype.subscribeCore = function (o) {\n this._o = o;\n return this._s.scheduleRecursive(this, scheduleRecursive);\n };\n\n return GenerateObservable;\n }(ObservableBase));\n\n /**\n * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.\n *\n * @example\n * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });\n * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);\n * @param {Mixed} initialState Initial state.\n * @param {Function} condition Condition to terminate generation (upon returning false).\n * @param {Function} iterate Iteration step function.\n * @param {Function} resultSelector Selector function for results produced in the sequence.\n * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.\n * @returns {Observable} The generated sequence.\n */\n Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);\n };\n\n function observableOf (scheduler, array) {\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new FromArrayObservable(array, scheduler);\n }\n\n /**\n * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.\n * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.\n */\n Observable.of = function () {\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return new FromArrayObservable(args, currentThreadScheduler);\n };\n\n /**\n * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.\n * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.\n * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.\n */\n Observable.ofWithScheduler = function (scheduler) {\n var len = arguments.length, args = new Array(len - 1);\n for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }\n return new FromArrayObservable(args, scheduler);\n };\n\n /**\n * Creates an Observable sequence from changes to an array using Array.observe.\n * @param {Array} array An array to observe changes.\n * @returns {Observable} An observable sequence containing changes to an array from Array.observe.\n */\n Observable.ofArrayChanges = function(array) {\n if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }\n if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }\n return new AnonymousObservable(function(observer) {\n function observerFn(changes) {\n for(var i = 0, len = changes.length; i < len; i++) {\n observer.onNext(changes[i]);\n }\n }\n \n Array.observe(array, observerFn);\n\n return function () {\n Array.unobserve(array, observerFn);\n };\n });\n };\n\n /**\n * Creates an Observable sequence from changes to an object using Object.observe.\n * @param {Object} obj An object to observe changes.\n * @returns {Observable} An observable sequence containing changes to an object from Object.observe.\n */\n Observable.ofObjectChanges = function(obj) {\n if (obj == null) { throw new TypeError('object must not be null or undefined.'); }\n if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') }\n return new AnonymousObservable(function(observer) {\n function observerFn(changes) {\n for(var i = 0, len = changes.length; i < len; i++) {\n observer.onNext(changes[i]);\n }\n }\n\n Object.observe(obj, observerFn);\n\n return function () {\n Object.unobserve(obj, observerFn);\n };\n });\n };\n\n var NeverObservable = (function(__super__) {\n inherits(NeverObservable, __super__);\n function NeverObservable() {\n __super__.call(this);\n }\n\n NeverObservable.prototype.subscribeCore = function (observer) {\n return disposableEmpty;\n };\n\n return NeverObservable;\n }(ObservableBase));\n\n var NEVER_OBSERVABLE = new NeverObservable();\n\n /**\n * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).\n * @returns {Observable} An observable sequence whose observers will never get called.\n */\n var observableNever = Observable.never = function () {\n return NEVER_OBSERVABLE;\n };\n\n var PairsObservable = (function(__super__) {\n inherits(PairsObservable, __super__);\n function PairsObservable(o, scheduler) {\n this._o = o;\n this._keys = Object.keys(o);\n this._scheduler = scheduler;\n __super__.call(this);\n }\n\n function scheduleMethod(o, obj, keys) {\n return function loopRecursive(i, recurse) {\n if (i < keys.length) {\n var key = keys[i];\n o.onNext([key, obj[key]]);\n recurse(i + 1);\n } else {\n o.onCompleted();\n }\n };\n }\n\n PairsObservable.prototype.subscribeCore = function (o) {\n return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));\n };\n\n return PairsObservable;\n }(ObservableBase));\n\n /**\n * Convert an object into an observable sequence of [key, value] pairs.\n * @param {Object} obj The object to inspect.\n * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.\n * @returns {Observable} An observable sequence of [key, value] pairs from the object.\n */\n Observable.pairs = function (obj, scheduler) {\n scheduler || (scheduler = currentThreadScheduler);\n return new PairsObservable(obj, scheduler);\n };\n\n var RangeObservable = (function(__super__) {\n inherits(RangeObservable, __super__);\n function RangeObservable(start, count, scheduler) {\n this.start = start;\n this.rangeCount = count;\n this.scheduler = scheduler;\n __super__.call(this);\n }\n\n function loopRecursive(start, count, o) {\n return function loop (i, recurse) {\n if (i < count) {\n o.onNext(start + i);\n recurse(i + 1);\n } else {\n o.onCompleted();\n }\n };\n }\n\n RangeObservable.prototype.subscribeCore = function (o) {\n return this.scheduler.scheduleRecursive(\n 0,\n loopRecursive(this.start, this.rangeCount, o)\n );\n };\n\n return RangeObservable;\n }(ObservableBase));\n\n /**\n * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.\n * @param {Number} start The value of the first integer in the sequence.\n * @param {Number} count The number of sequential integers to generate.\n * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.\n * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.\n */\n Observable.range = function (start, count, scheduler) {\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new RangeObservable(start, count, scheduler);\n };\n\n var RepeatObservable = (function(__super__) {\n inherits(RepeatObservable, __super__);\n function RepeatObservable(value, repeatCount, scheduler) {\n this.value = value;\n this.repeatCount = repeatCount == null ? -1 : repeatCount;\n this.scheduler = scheduler;\n __super__.call(this);\n }\n\n RepeatObservable.prototype.subscribeCore = function (observer) {\n var sink = new RepeatSink(observer, this);\n return sink.run();\n };\n\n return RepeatObservable;\n }(ObservableBase));\n\n function RepeatSink(observer, parent) {\n this.observer = observer;\n this.parent = parent;\n }\n\n RepeatSink.prototype.run = function () {\n var observer = this.observer, value = this.parent.value;\n function loopRecursive(i, recurse) {\n if (i === -1 || i > 0) {\n observer.onNext(value);\n i > 0 && i--;\n }\n if (i === 0) { return observer.onCompleted(); }\n recurse(i);\n }\n\n return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);\n };\n\n /**\n * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.\n * @param {Mixed} value Element to repeat.\n * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.\n * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.\n * @returns {Observable} An observable sequence that repeats the given element the specified number of times.\n */\n Observable.repeat = function (value, repeatCount, scheduler) {\n isScheduler(scheduler) || (scheduler = currentThreadScheduler);\n return new RepeatObservable(value, repeatCount, scheduler);\n };\n\n var JustObservable = (function(__super__) {\n inherits(JustObservable, __super__);\n function JustObservable(value, scheduler) {\n this._value = value;\n this._scheduler = scheduler;\n __super__.call(this);\n }\n\n JustObservable.prototype.subscribeCore = function (o) {\n var state = [this._value, o];\n return this._scheduler === immediateScheduler ?\n scheduleItem(null, state) :\n this._scheduler.schedule(state, scheduleItem);\n };\n\n function scheduleItem(s, state) {\n var value = state[0], observer = state[1];\n observer.onNext(value);\n observer.onCompleted();\n return disposableEmpty;\n }\n\n return JustObservable;\n }(ObservableBase));\n\n /**\n * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.\n * There is an alias called 'just' or browsers 0) {\n this.parent.handleSubscribe(this.parent.q.shift());\n } else {\n this.parent.activeCount--;\n this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();\n }\n };\n\n return MergeObserver;\n }(AbstractObserver));\n\n /**\n * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.\n * Or merges two observable sequences into a single observable sequence.\n * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.\n * @returns {Observable} The observable sequence that merges the elements of the inner sequences.\n */\n observableProto.merge = function (maxConcurrentOrOther) {\n return typeof maxConcurrentOrOther !== 'number' ?\n observableMerge(this, maxConcurrentOrOther) :\n new MergeObservable(this, maxConcurrentOrOther);\n };\n\n /**\n * Merges all the observable sequences into a single observable sequence.\n * The scheduler is optional and if not specified, the immediate scheduler is used.\n * @returns {Observable} The observable sequence that merges the elements of the observable sequences.\n */\n var observableMerge = Observable.merge = function () {\n var scheduler, sources = [], i, len = arguments.length;\n if (!arguments[0]) {\n scheduler = immediateScheduler;\n for(i = 1; i < len; i++) { sources.push(arguments[i]); }\n } else if (isScheduler(arguments[0])) {\n scheduler = arguments[0];\n for(i = 1; i < len; i++) { sources.push(arguments[i]); }\n } else {\n scheduler = immediateScheduler;\n for(i = 0; i < len; i++) { sources.push(arguments[i]); }\n }\n if (Array.isArray(sources[0])) {\n sources = sources[0];\n }\n return observableOf(scheduler, sources).mergeAll();\n };\n\n var MergeAllObservable = (function (__super__) {\n inherits(MergeAllObservable, __super__);\n\n function MergeAllObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n MergeAllObservable.prototype.subscribeCore = function (o) {\n var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();\n g.add(m);\n m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));\n return g;\n };\n\n return MergeAllObservable;\n }(ObservableBase));\n\n var MergeAllObserver = (function (__super__) {\n function MergeAllObserver(o, g) {\n this.o = o;\n this.g = g;\n this.done = false;\n __super__.call(this);\n }\n\n inherits(MergeAllObserver, __super__);\n\n MergeAllObserver.prototype.next = function(innerSource) {\n var sad = new SingleAssignmentDisposable();\n this.g.add(sad);\n isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));\n sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));\n };\n\n MergeAllObserver.prototype.error = function (e) {\n this.o.onError(e);\n };\n\n MergeAllObserver.prototype.completed = function () {\n this.done = true;\n this.g.length === 1 && this.o.onCompleted();\n };\n\n function InnerObserver(parent, sad) {\n this.parent = parent;\n this.sad = sad;\n __super__.call(this);\n }\n\n inherits(InnerObserver, __super__);\n\n InnerObserver.prototype.next = function (x) {\n this.parent.o.onNext(x);\n };\n InnerObserver.prototype.error = function (e) {\n this.parent.o.onError(e);\n };\n InnerObserver.prototype.completed = function () {\n this.parent.g.remove(this.sad);\n this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();\n };\n\n return MergeAllObserver;\n }(AbstractObserver));\n\n /**\n * Merges an observable sequence of observable sequences into an observable sequence.\n * @returns {Observable} The observable sequence that merges the elements of the inner sequences.\n */\n observableProto.mergeAll = function () {\n return new MergeAllObservable(this);\n };\n\n var CompositeError = Rx.CompositeError = function(errors) {\n this.innerErrors = errors;\n this.message = 'This contains multiple errors. Check the innerErrors';\n Error.call(this);\n };\n CompositeError.prototype = Object.create(Error.prototype);\n CompositeError.prototype.name = 'CompositeError';\n\n var MergeDelayErrorObservable = (function(__super__) {\n inherits(MergeDelayErrorObservable, __super__);\n function MergeDelayErrorObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n MergeDelayErrorObservable.prototype.subscribeCore = function (o) {\n var group = new CompositeDisposable(),\n m = new SingleAssignmentDisposable(),\n state = { isStopped: false, errors: [], o: o };\n\n group.add(m);\n m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));\n\n return group;\n };\n\n return MergeDelayErrorObservable;\n }(ObservableBase));\n\n var MergeDelayErrorObserver = (function(__super__) {\n inherits(MergeDelayErrorObserver, __super__);\n function MergeDelayErrorObserver(group, state) {\n this._group = group;\n this._state = state;\n __super__.call(this);\n }\n\n function setCompletion(o, errors) {\n if (errors.length === 0) {\n o.onCompleted();\n } else if (errors.length === 1) {\n o.onError(errors[0]);\n } else {\n o.onError(new CompositeError(errors));\n }\n }\n\n MergeDelayErrorObserver.prototype.next = function (x) {\n var inner = new SingleAssignmentDisposable();\n this._group.add(inner);\n\n // Check for promises support\n isPromise(x) && (x = observableFromPromise(x));\n inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));\n };\n\n MergeDelayErrorObserver.prototype.error = function (e) {\n this._state.errors.push(e);\n this._state.isStopped = true;\n this._group.length === 1 && setCompletion(this._state.o, this._state.errors);\n };\n\n MergeDelayErrorObserver.prototype.completed = function () {\n this._state.isStopped = true;\n this._group.length === 1 && setCompletion(this._state.o, this._state.errors);\n };\n\n inherits(InnerObserver, __super__);\n function InnerObserver(inner, group, state) {\n this._inner = inner;\n this._group = group;\n this._state = state;\n __super__.call(this);\n }\n\n InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };\n InnerObserver.prototype.error = function (e) {\n this._state.errors.push(e);\n this._group.remove(this._inner);\n this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);\n };\n InnerObserver.prototype.completed = function () {\n this._group.remove(this._inner);\n this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);\n };\n\n return MergeDelayErrorObserver;\n }(AbstractObserver));\n\n /**\n * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to\n * receive all successfully emitted items from all of the source Observables without being interrupted by\n * an error notification from one of them.\n *\n * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an\n * error via the Observer's onError, mergeDelayError will refrain from propagating that\n * error notification until all of the merged Observables have finished emitting items.\n * @param {Array | Arguments} args Arguments or an array to merge.\n * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable\n */\n Observable.mergeDelayError = function() {\n var args;\n if (Array.isArray(arguments[0])) {\n args = arguments[0];\n } else {\n var len = arguments.length;\n args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n }\n var source = observableOf(null, args);\n return new MergeDelayErrorObservable(source);\n };\n\n /**\n * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.\n * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.\n * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.\n */\n observableProto.onErrorResumeNext = function (second) {\n if (!second) { throw new Error('Second observable is required'); }\n return onErrorResumeNext([this, second]);\n };\n\n var OnErrorResumeNextObservable = (function(__super__) {\n inherits(OnErrorResumeNextObservable, __super__);\n function OnErrorResumeNextObservable(sources) {\n this.sources = sources;\n __super__.call(this);\n }\n\n function scheduleMethod(state, recurse) {\n if (state.pos < state.sources.length) {\n var current = state.sources[state.pos++];\n isPromise(current) && (current = observableFromPromise(current));\n var d = new SingleAssignmentDisposable();\n state.subscription.setDisposable(d);\n d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));\n } else {\n state.o.onCompleted();\n }\n }\n\n OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {\n var subscription = new SerialDisposable(),\n state = {pos: 0, subscription: subscription, o: o, sources: this.sources },\n cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);\n\n return new BinaryDisposable(subscription, cancellable);\n };\n\n return OnErrorResumeNextObservable;\n }(ObservableBase));\n\n var OnErrorResumeNextObserver = (function(__super__) {\n inherits(OnErrorResumeNextObserver, __super__);\n function OnErrorResumeNextObserver(state, recurse) {\n this._state = state;\n this._recurse = recurse;\n __super__.call(this);\n }\n\n OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };\n OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };\n OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };\n\n return OnErrorResumeNextObserver;\n }(AbstractObserver));\n\n /**\n * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.\n * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.\n */\n var onErrorResumeNext = Observable.onErrorResumeNext = function () {\n var sources = [];\n if (Array.isArray(arguments[0])) {\n sources = arguments[0];\n } else {\n var len = arguments.length;\n sources = new Array(len);\n for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }\n }\n return new OnErrorResumeNextObservable(sources);\n };\n\n var SkipUntilObservable = (function(__super__) {\n inherits(SkipUntilObservable, __super__);\n\n function SkipUntilObservable(source, other) {\n this._s = source;\n this._o = isPromise(other) ? observableFromPromise(other) : other;\n this._open = false;\n __super__.call(this);\n }\n\n SkipUntilObservable.prototype.subscribeCore = function(o) {\n var leftSubscription = new SingleAssignmentDisposable();\n leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));\n\n isPromise(this._o) && (this._o = observableFromPromise(this._o));\n\n var rightSubscription = new SingleAssignmentDisposable();\n rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));\n\n return new BinaryDisposable(leftSubscription, rightSubscription);\n };\n\n return SkipUntilObservable;\n }(ObservableBase));\n\n var SkipUntilSourceObserver = (function(__super__) {\n inherits(SkipUntilSourceObserver, __super__);\n function SkipUntilSourceObserver(o, p) {\n this._o = o;\n this._p = p;\n __super__.call(this);\n }\n\n SkipUntilSourceObserver.prototype.next = function (x) {\n this._p._open && this._o.onNext(x);\n };\n\n SkipUntilSourceObserver.prototype.error = function (err) {\n this._o.onError(err);\n };\n\n SkipUntilSourceObserver.prototype.onCompleted = function () {\n this._p._open && this._o.onCompleted();\n };\n\n return SkipUntilSourceObserver;\n }(AbstractObserver));\n\n var SkipUntilOtherObserver = (function(__super__) {\n inherits(SkipUntilOtherObserver, __super__);\n function SkipUntilOtherObserver(o, p, r) {\n this._o = o;\n this._p = p;\n this._r = r;\n __super__.call(this);\n }\n\n SkipUntilOtherObserver.prototype.next = function () {\n this._p._open = true;\n this._r.dispose();\n };\n\n SkipUntilOtherObserver.prototype.error = function (err) {\n this._o.onError(err);\n };\n\n SkipUntilOtherObserver.prototype.onCompleted = function () {\n this._r.dispose();\n };\n\n return SkipUntilOtherObserver;\n }(AbstractObserver));\n\n /**\n * Returns the values from the source observable sequence only after the other observable sequence produces a value.\n * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.\n * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.\n */\n observableProto.skipUntil = function (other) {\n return new SkipUntilObservable(this, other);\n };\n\n var SwitchObservable = (function(__super__) {\n inherits(SwitchObservable, __super__);\n function SwitchObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n SwitchObservable.prototype.subscribeCore = function (o) {\n var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));\n return new BinaryDisposable(s, inner);\n };\n\n inherits(SwitchObserver, AbstractObserver);\n function SwitchObserver(o, inner) {\n this.o = o;\n this.inner = inner;\n this.stopped = false;\n this.latest = 0;\n this.hasLatest = false;\n AbstractObserver.call(this);\n }\n\n SwitchObserver.prototype.next = function (innerSource) {\n var d = new SingleAssignmentDisposable(), id = ++this.latest;\n this.hasLatest = true;\n this.inner.setDisposable(d);\n isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));\n d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));\n };\n\n SwitchObserver.prototype.error = function (e) {\n this.o.onError(e);\n };\n\n SwitchObserver.prototype.completed = function () {\n this.stopped = true;\n !this.hasLatest && this.o.onCompleted();\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(parent, id) {\n this.parent = parent;\n this.id = id;\n AbstractObserver.call(this);\n }\n InnerObserver.prototype.next = function (x) {\n this.parent.latest === this.id && this.parent.o.onNext(x);\n };\n\n InnerObserver.prototype.error = function (e) {\n this.parent.latest === this.id && this.parent.o.onError(e);\n };\n\n InnerObserver.prototype.completed = function () {\n if (this.parent.latest === this.id) {\n this.parent.hasLatest = false;\n this.parent.stopped && this.parent.o.onCompleted();\n }\n };\n\n return SwitchObservable;\n }(ObservableBase));\n\n /**\n * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.\n * @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.\n */\n observableProto['switch'] = observableProto.switchLatest = function () {\n return new SwitchObservable(this);\n };\n\n var TakeUntilObservable = (function(__super__) {\n inherits(TakeUntilObservable, __super__);\n\n function TakeUntilObservable(source, other) {\n this.source = source;\n this.other = isPromise(other) ? observableFromPromise(other) : other;\n __super__.call(this);\n }\n\n TakeUntilObservable.prototype.subscribeCore = function(o) {\n return new BinaryDisposable(\n this.source.subscribe(o),\n this.other.subscribe(new TakeUntilObserver(o))\n );\n };\n\n return TakeUntilObservable;\n }(ObservableBase));\n\n var TakeUntilObserver = (function(__super__) {\n inherits(TakeUntilObserver, __super__);\n function TakeUntilObserver(o) {\n this._o = o;\n __super__.call(this);\n }\n\n TakeUntilObserver.prototype.next = function () {\n this._o.onCompleted();\n };\n\n TakeUntilObserver.prototype.error = function (err) {\n this._o.onError(err);\n };\n\n TakeUntilObserver.prototype.onCompleted = noop;\n\n return TakeUntilObserver;\n }(AbstractObserver));\n\n /**\n * Returns the values from the source observable sequence until the other observable sequence produces a value.\n * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.\n * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.\n */\n observableProto.takeUntil = function (other) {\n return new TakeUntilObservable(this, other);\n };\n\n function falseFactory() { return false; }\n function argumentsToArray() {\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return args;\n }\n\n var WithLatestFromObservable = (function(__super__) {\n inherits(WithLatestFromObservable, __super__);\n function WithLatestFromObservable(source, sources, resultSelector) {\n this._s = source;\n this._ss = sources;\n this._cb = resultSelector;\n __super__.call(this);\n }\n\n WithLatestFromObservable.prototype.subscribeCore = function (o) {\n var len = this._ss.length;\n var state = {\n hasValue: arrayInitialize(len, falseFactory),\n hasValueAll: false,\n values: new Array(len)\n };\n\n var n = this._ss.length, subscriptions = new Array(n + 1);\n for (var i = 0; i < n; i++) {\n var other = this._ss[i], sad = new SingleAssignmentDisposable();\n isPromise(other) && (other = observableFromPromise(other));\n sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));\n subscriptions[i] = sad;\n }\n\n var outerSad = new SingleAssignmentDisposable();\n outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));\n subscriptions[n] = outerSad;\n\n return new NAryDisposable(subscriptions);\n };\n\n return WithLatestFromObservable;\n }(ObservableBase));\n\n var WithLatestFromOtherObserver = (function (__super__) {\n inherits(WithLatestFromOtherObserver, __super__);\n function WithLatestFromOtherObserver(o, i, state) {\n this._o = o;\n this._i = i;\n this._state = state;\n __super__.call(this);\n }\n\n WithLatestFromOtherObserver.prototype.next = function (x) {\n this._state.values[this._i] = x;\n this._state.hasValue[this._i] = true;\n this._state.hasValueAll = this._state.hasValue.every(identity);\n };\n\n WithLatestFromOtherObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n WithLatestFromOtherObserver.prototype.completed = noop;\n\n return WithLatestFromOtherObserver;\n }(AbstractObserver));\n\n var WithLatestFromSourceObserver = (function (__super__) {\n inherits(WithLatestFromSourceObserver, __super__);\n function WithLatestFromSourceObserver(o, cb, state) {\n this._o = o;\n this._cb = cb;\n this._state = state;\n __super__.call(this);\n }\n\n WithLatestFromSourceObserver.prototype.next = function (x) {\n var allValues = [x].concat(this._state.values);\n if (!this._state.hasValueAll) { return; }\n var res = tryCatch(this._cb).apply(null, allValues);\n if (res === errorObj) { return this._o.onError(res.e); }\n this._o.onNext(res);\n };\n\n WithLatestFromSourceObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n WithLatestFromSourceObserver.prototype.completed = function () {\n this._o.onCompleted();\n };\n\n return WithLatestFromSourceObserver;\n }(AbstractObserver));\n\n /**\n * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.\n * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.\n */\n observableProto.withLatestFrom = function () {\n if (arguments.length === 0) { throw new Error('invalid arguments'); }\n\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;\n Array.isArray(args[0]) && (args = args[0]);\n\n return new WithLatestFromObservable(this, args, resultSelector);\n };\n\n function falseFactory() { return false; }\n function emptyArrayFactory() { return []; }\n\n var ZipObservable = (function(__super__) {\n inherits(ZipObservable, __super__);\n function ZipObservable(sources, resultSelector) {\n this._s = sources;\n this._cb = resultSelector;\n __super__.call(this);\n }\n\n ZipObservable.prototype.subscribeCore = function(observer) {\n var n = this._s.length,\n subscriptions = new Array(n),\n done = arrayInitialize(n, falseFactory),\n q = arrayInitialize(n, emptyArrayFactory);\n\n for (var i = 0; i < n; i++) {\n var source = this._s[i], sad = new SingleAssignmentDisposable();\n subscriptions[i] = sad;\n isPromise(source) && (source = observableFromPromise(source));\n sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));\n }\n\n return new NAryDisposable(subscriptions);\n };\n\n return ZipObservable;\n }(ObservableBase));\n\n var ZipObserver = (function (__super__) {\n inherits(ZipObserver, __super__);\n function ZipObserver(o, i, p, q, d) {\n this._o = o;\n this._i = i;\n this._p = p;\n this._q = q;\n this._d = d;\n __super__.call(this);\n }\n\n function notEmpty(x) { return x.length > 0; }\n function shiftEach(x) { return x.shift(); }\n function notTheSame(i) {\n return function (x, j) {\n return j !== i;\n };\n }\n\n ZipObserver.prototype.next = function (x) {\n this._q[this._i].push(x);\n if (this._q.every(notEmpty)) {\n var queuedValues = this._q.map(shiftEach);\n var res = tryCatch(this._p._cb).apply(null, queuedValues);\n if (res === errorObj) { return this._o.onError(res.e); }\n this._o.onNext(res);\n } else if (this._d.filter(notTheSame(this._i)).every(identity)) {\n this._o.onCompleted();\n }\n };\n\n ZipObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ZipObserver.prototype.completed = function () {\n this._d[this._i] = true;\n this._d.every(identity) && this._o.onCompleted();\n };\n\n return ZipObserver;\n }(AbstractObserver));\n\n /**\n * 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.\n * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.\n * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.\n */\n observableProto.zip = function () {\n if (arguments.length === 0) { throw new Error('invalid arguments'); }\n\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;\n Array.isArray(args[0]) && (args = args[0]);\n\n var parent = this;\n args.unshift(parent);\n\n return new ZipObservable(args, resultSelector);\n };\n\n /**\n * 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.\n * @param arguments Observable sources.\n * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.\n * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.\n */\n Observable.zip = function () {\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n if (Array.isArray(args[0])) {\n args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];\n }\n var first = args.shift();\n return first.zip.apply(first, args);\n };\n\nfunction falseFactory() { return false; }\nfunction emptyArrayFactory() { return []; }\nfunction argumentsToArray() {\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return args;\n}\n\nvar ZipIterableObservable = (function(__super__) {\n inherits(ZipIterableObservable, __super__);\n function ZipIterableObservable(sources, cb) {\n this.sources = sources;\n this._cb = cb;\n __super__.call(this);\n }\n\n ZipIterableObservable.prototype.subscribeCore = function (o) {\n var sources = this.sources, len = sources.length, subscriptions = new Array(len);\n\n var state = {\n q: arrayInitialize(len, emptyArrayFactory),\n done: arrayInitialize(len, falseFactory),\n cb: this._cb,\n o: o\n };\n\n for (var i = 0; i < len; i++) {\n (function (i) {\n var source = sources[i], sad = new SingleAssignmentDisposable();\n (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));\n\n subscriptions[i] = sad;\n sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));\n }(i));\n }\n\n return new NAryDisposable(subscriptions);\n };\n\n return ZipIterableObservable;\n}(ObservableBase));\n\nvar ZipIterableObserver = (function (__super__) {\n inherits(ZipIterableObserver, __super__);\n function ZipIterableObserver(s, i) {\n this._s = s;\n this._i = i;\n __super__.call(this);\n }\n\n function notEmpty(x) { return x.length > 0; }\n function shiftEach(x) { return x.shift(); }\n function notTheSame(i) {\n return function (x, j) {\n return j !== i;\n };\n }\n\n ZipIterableObserver.prototype.next = function (x) {\n this._s.q[this._i].push(x);\n if (this._s.q.every(notEmpty)) {\n var queuedValues = this._s.q.map(shiftEach),\n res = tryCatch(this._s.cb).apply(null, queuedValues);\n if (res === errorObj) { return this._s.o.onError(res.e); }\n this._s.o.onNext(res);\n } else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {\n this._s.o.onCompleted();\n }\n };\n\n ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };\n\n ZipIterableObserver.prototype.completed = function () {\n this._s.done[this._i] = true;\n this._s.done.every(identity) && this._s.o.onCompleted();\n };\n\n return ZipIterableObserver;\n}(AbstractObserver));\n\n/**\n * 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.\n * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.\n * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.\n */\nobservableProto.zipIterable = function () {\n if (arguments.length === 0) { throw new Error('invalid arguments'); }\n\n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;\n\n var parent = this;\n args.unshift(parent);\n return new ZipIterableObservable(args, resultSelector);\n};\n\n function asObservable(source) {\n return function subscribe(o) { return source.subscribe(o); };\n }\n\n /**\n * Hides the identity of an observable sequence.\n * @returns {Observable} An observable sequence that hides the identity of the source sequence.\n */\n observableProto.asObservable = function () {\n return new AnonymousObservable(asObservable(this), this);\n };\n\n function toArray(x) { return x.toArray(); }\n function notEmpty(x) { return x.length > 0; }\n\n /**\n * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.\n * @param {Number} count Length of each buffer.\n * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.\n * @returns {Observable} An observable sequence of buffers.\n */\n observableProto.bufferWithCount = function (count, skip) {\n typeof skip !== 'number' && (skip = count);\n return this.windowWithCount(count, skip)\n .flatMap(toArray)\n .filter(notEmpty);\n };\n\n var DematerializeObservable = (function (__super__) {\n inherits(DematerializeObservable, __super__);\n function DematerializeObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n DematerializeObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new DematerializeObserver(o));\n };\n\n return DematerializeObservable;\n }(ObservableBase));\n\n var DematerializeObserver = (function (__super__) {\n inherits(DematerializeObserver, __super__);\n\n function DematerializeObserver(o) {\n this._o = o;\n __super__.call(this);\n }\n\n DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };\n DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };\n DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return DematerializeObserver;\n }(AbstractObserver));\n\n /**\n * Dematerializes the explicit notification values of an observable sequence as implicit notifications.\n * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.\n */\n observableProto.dematerialize = function () {\n return new DematerializeObservable(this);\n };\n\n var DistinctUntilChangedObservable = (function(__super__) {\n inherits(DistinctUntilChangedObservable, __super__);\n function DistinctUntilChangedObservable(source, keyFn, comparer) {\n this.source = source;\n this.keyFn = keyFn;\n this.comparer = comparer;\n __super__.call(this);\n }\n\n DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));\n };\n\n return DistinctUntilChangedObservable;\n }(ObservableBase));\n\n var DistinctUntilChangedObserver = (function(__super__) {\n inherits(DistinctUntilChangedObserver, __super__);\n function DistinctUntilChangedObserver(o, keyFn, comparer) {\n this.o = o;\n this.keyFn = keyFn;\n this.comparer = comparer;\n this.hasCurrentKey = false;\n this.currentKey = null;\n __super__.call(this);\n }\n\n DistinctUntilChangedObserver.prototype.next = function (x) {\n var key = x, comparerEquals;\n if (isFunction(this.keyFn)) {\n key = tryCatch(this.keyFn)(x);\n if (key === errorObj) { return this.o.onError(key.e); }\n }\n if (this.hasCurrentKey) {\n comparerEquals = tryCatch(this.comparer)(this.currentKey, key);\n if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }\n }\n if (!this.hasCurrentKey || !comparerEquals) {\n this.hasCurrentKey = true;\n this.currentKey = key;\n this.o.onNext(x);\n }\n };\n DistinctUntilChangedObserver.prototype.error = function(e) {\n this.o.onError(e);\n };\n DistinctUntilChangedObserver.prototype.completed = function () {\n this.o.onCompleted();\n };\n\n return DistinctUntilChangedObserver;\n }(AbstractObserver));\n\n /**\n * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.\n * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.\n * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.\n * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.\n */\n observableProto.distinctUntilChanged = function (keyFn, comparer) {\n comparer || (comparer = defaultComparer);\n return new DistinctUntilChangedObservable(this, keyFn, comparer);\n };\n\n var TapObservable = (function(__super__) {\n inherits(TapObservable,__super__);\n function TapObservable(source, observerOrOnNext, onError, onCompleted) {\n this.source = source;\n this._oN = observerOrOnNext;\n this._oE = onError;\n this._oC = onCompleted;\n __super__.call(this);\n }\n\n TapObservable.prototype.subscribeCore = function(o) {\n return this.source.subscribe(new InnerObserver(o, this));\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(o, p) {\n this.o = o;\n this.t = !p._oN || isFunction(p._oN) ?\n observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :\n p._oN;\n this.isStopped = false;\n AbstractObserver.call(this);\n }\n InnerObserver.prototype.next = function(x) {\n var res = tryCatch(this.t.onNext).call(this.t, x);\n if (res === errorObj) { this.o.onError(res.e); }\n this.o.onNext(x);\n };\n InnerObserver.prototype.error = function(err) {\n var res = tryCatch(this.t.onError).call(this.t, err);\n if (res === errorObj) { return this.o.onError(res.e); }\n this.o.onError(err);\n };\n InnerObserver.prototype.completed = function() {\n var res = tryCatch(this.t.onCompleted).call(this.t);\n if (res === errorObj) { return this.o.onError(res.e); }\n this.o.onCompleted();\n };\n\n return TapObservable;\n }(ObservableBase));\n\n /**\n * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.\n * 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.\n * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.\n * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.\n * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.\n * @returns {Observable} The source sequence with the side-effecting behavior applied.\n */\n observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {\n return new TapObservable(this, observerOrOnNext, onError, onCompleted);\n };\n\n /**\n * Invokes an action for each element in the observable sequence.\n * 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.\n * @param {Function} onNext Action to invoke for each element in the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} The source sequence with the side-effecting behavior applied.\n */\n observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {\n return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);\n };\n\n /**\n * Invokes an action upon exceptional termination of the observable sequence.\n * 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.\n * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} The source sequence with the side-effecting behavior applied.\n */\n observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {\n return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);\n };\n\n /**\n * Invokes an action upon graceful termination of the observable sequence.\n * 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.\n * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} The source sequence with the side-effecting behavior applied.\n */\n observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {\n return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);\n };\n\n var FinallyObservable = (function (__super__) {\n inherits(FinallyObservable, __super__);\n function FinallyObservable(source, fn, thisArg) {\n this.source = source;\n this._fn = bindCallback(fn, thisArg, 0);\n __super__.call(this);\n }\n\n FinallyObservable.prototype.subscribeCore = function (o) {\n var d = tryCatch(this.source.subscribe).call(this.source, o);\n if (d === errorObj) {\n this._fn();\n thrower(d.e);\n }\n\n return new FinallyDisposable(d, this._fn);\n };\n\n function FinallyDisposable(s, fn) {\n this.isDisposed = false;\n this._s = s;\n this._fn = fn;\n }\n FinallyDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n var res = tryCatch(this._s.dispose).call(this._s);\n this._fn();\n res === errorObj && thrower(res.e);\n }\n };\n\n return FinallyObservable;\n\n }(ObservableBase));\n\n /**\n * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.\n * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.\n * @returns {Observable} Source sequence with the action-invoking termination behavior applied.\n */\n observableProto['finally'] = function (action, thisArg) {\n return new FinallyObservable(this, action, thisArg);\n };\n\n var IgnoreElementsObservable = (function(__super__) {\n inherits(IgnoreElementsObservable, __super__);\n\n function IgnoreElementsObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n IgnoreElementsObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new InnerObserver(o));\n };\n\n function InnerObserver(o) {\n this.o = o;\n this.isStopped = false;\n }\n InnerObserver.prototype.onNext = noop;\n InnerObserver.prototype.onError = function (err) {\n if(!this.isStopped) {\n this.isStopped = true;\n this.o.onError(err);\n }\n };\n InnerObserver.prototype.onCompleted = function () {\n if(!this.isStopped) {\n this.isStopped = true;\n this.o.onCompleted();\n }\n };\n InnerObserver.prototype.dispose = function() { this.isStopped = true; };\n InnerObserver.prototype.fail = function (e) {\n if (!this.isStopped) {\n this.isStopped = true;\n this.observer.onError(e);\n return true;\n }\n\n return false;\n };\n\n return IgnoreElementsObservable;\n }(ObservableBase));\n\n /**\n * Ignores all elements in an observable sequence leaving only the termination messages.\n * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.\n */\n observableProto.ignoreElements = function () {\n return new IgnoreElementsObservable(this);\n };\n\n var MaterializeObservable = (function (__super__) {\n inherits(MaterializeObservable, __super__);\n function MaterializeObservable(source, fn) {\n this.source = source;\n __super__.call(this);\n }\n\n MaterializeObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new MaterializeObserver(o));\n };\n\n return MaterializeObservable;\n }(ObservableBase));\n\n var MaterializeObserver = (function (__super__) {\n inherits(MaterializeObserver, __super__);\n\n function MaterializeObserver(o) {\n this._o = o;\n __super__.call(this);\n }\n\n MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };\n MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };\n MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };\n\n return MaterializeObserver;\n }(AbstractObserver));\n\n /**\n * Materializes the implicit notifications of an observable sequence as explicit notification values.\n * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.\n */\n observableProto.materialize = function () {\n return new MaterializeObservable(this);\n };\n\n /**\n * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.\n * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.\n * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.\n */\n observableProto.repeat = function (repeatCount) {\n return enumerableRepeat(this, repeatCount).concat();\n };\n\n /**\n * 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.\n * Note if you encounter an error and want it to retry once, then you must use .retry(2);\n *\n * @example\n * var res = retried = retry.repeat();\n * var res = retried = retry.repeat(2);\n * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.\n * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.\n */\n observableProto.retry = function (retryCount) {\n return enumerableRepeat(this, retryCount).catchError();\n };\n\n /**\n * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. \n * if the notifier completes, the observable sequence completes.\n *\n * @example\n * var timer = Observable.timer(500);\n * var source = observable.retryWhen(timer);\n * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.\n * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.\n */\n observableProto.retryWhen = function (notifier) {\n return enumerableRepeat(this).catchErrorWhen(notifier);\n };\n var ScanObservable = (function(__super__) {\n inherits(ScanObservable, __super__);\n function ScanObservable(source, accumulator, hasSeed, seed) {\n this.source = source;\n this.accumulator = accumulator;\n this.hasSeed = hasSeed;\n this.seed = seed;\n __super__.call(this);\n }\n\n ScanObservable.prototype.subscribeCore = function(o) {\n return this.source.subscribe(new ScanObserver(o,this));\n };\n\n return ScanObservable;\n }(ObservableBase));\n\n var ScanObserver = (function (__super__) {\n inherits(ScanObserver, __super__);\n function ScanObserver(o, parent) {\n this._o = o;\n this._p = parent;\n this._fn = parent.accumulator;\n this._hs = parent.hasSeed;\n this._s = parent.seed;\n this._ha = false;\n this._a = null;\n this._hv = false;\n this._i = 0;\n __super__.call(this);\n }\n\n ScanObserver.prototype.next = function (x) {\n !this._hv && (this._hv = true);\n if (this._ha) {\n this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);\n } else {\n this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;\n this._ha = true;\n }\n if (this._a === errorObj) { return this._o.onError(this._a.e); }\n this._o.onNext(this._a);\n this._i++;\n };\n\n ScanObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ScanObserver.prototype.completed = function () {\n !this._hv && this._hs && this._o.onNext(this._s);\n this._o.onCompleted();\n };\n\n return ScanObserver;\n }(AbstractObserver));\n\n /**\n * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.\n * For aggregation behavior with no intermediate results, see Observable.aggregate.\n * @param {Mixed} [seed] The initial accumulator value.\n * @param {Function} accumulator An accumulator function to be invoked on each element.\n * @returns {Observable} An observable sequence containing the accumulated values.\n */\n observableProto.scan = function () {\n var hasSeed = false, seed, accumulator = arguments[0];\n if (arguments.length === 2) {\n hasSeed = true;\n seed = arguments[1];\n }\n return new ScanObservable(this, accumulator, hasSeed, seed);\n };\n\n var SkipLastObservable = (function (__super__) {\n inherits(SkipLastObservable, __super__);\n function SkipLastObservable(source, c) {\n this.source = source;\n this._c = c;\n __super__.call(this);\n }\n\n SkipLastObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SkipLastObserver(o, this._c));\n };\n\n return SkipLastObservable;\n }(ObservableBase));\n\n var SkipLastObserver = (function (__super__) {\n inherits(SkipLastObserver, __super__);\n function SkipLastObserver(o, c) {\n this._o = o;\n this._c = c;\n this._q = [];\n __super__.call(this);\n }\n\n SkipLastObserver.prototype.next = function (x) {\n this._q.push(x);\n this._q.length > this._c && this._o.onNext(this._q.shift());\n };\n\n SkipLastObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n SkipLastObserver.prototype.completed = function () {\n this._o.onCompleted();\n };\n\n return SkipLastObserver;\n }(AbstractObserver));\n\n /**\n * Bypasses a specified number of elements at the end of an observable sequence.\n * @description\n * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are\n * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.\n * @param count Number of elements to bypass at the end of the source sequence.\n * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.\n */\n observableProto.skipLast = function (count) {\n if (count < 0) { throw new ArgumentOutOfRangeError(); }\n return new SkipLastObservable(this, count);\n };\n\n /**\n * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.\n * @example\n * var res = source.startWith(1, 2, 3);\n * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);\n * @param {Arguments} args The specified values to prepend to the observable sequence\n * @returns {Observable} The source sequence prepended with the specified values.\n */\n observableProto.startWith = function () {\n var values, scheduler, start = 0;\n if (!!arguments.length && isScheduler(arguments[0])) {\n scheduler = arguments[0];\n start = 1;\n } else {\n scheduler = immediateScheduler;\n }\n for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }\n return enumerableOf([observableFromArray(args, scheduler), this]).concat();\n };\n\n var TakeLastObserver = (function (__super__) {\n inherits(TakeLastObserver, __super__);\n function TakeLastObserver(o, c) {\n this._o = o;\n this._c = c;\n this._q = [];\n __super__.call(this);\n }\n\n TakeLastObserver.prototype.next = function (x) {\n this._q.push(x);\n this._q.length > this._c && this._q.shift();\n };\n\n TakeLastObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n TakeLastObserver.prototype.completed = function () {\n while (this._q.length > 0) { this._o.onNext(this._q.shift()); }\n this._o.onCompleted();\n };\n\n return TakeLastObserver;\n }(AbstractObserver));\n\n /**\n * Returns a specified number of contiguous elements from the end of an observable sequence.\n * @description\n * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of\n * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.\n * @param {Number} count Number of elements to take from the end of the source sequence.\n * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.\n */\n observableProto.takeLast = function (count) {\n if (count < 0) { throw new ArgumentOutOfRangeError(); }\n var source = this;\n return new AnonymousObservable(function (o) {\n return source.subscribe(new TakeLastObserver(o, count));\n }, source);\n };\n\n var TakeLastBufferObserver = (function (__super__) {\n inherits(TakeLastBufferObserver, __super__);\n function TakeLastBufferObserver(o, c) {\n this._o = o;\n this._c = c;\n this._q = [];\n __super__.call(this);\n }\n\n TakeLastBufferObserver.prototype.next = function (x) {\n this._q.push(x);\n this._q.length > this._c && this._q.shift();\n };\n\n TakeLastBufferObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n TakeLastBufferObserver.prototype.completed = function () {\n this._o.onNext(this._q);\n this._o.onCompleted();\n };\n\n return TakeLastBufferObserver;\n }(AbstractObserver));\n\n /**\n * Returns an array with the specified number of contiguous elements from the end of an observable sequence.\n *\n * @description\n * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the\n * source sequence, this buffer is produced on the result sequence.\n * @param {Number} count Number of elements to take from the end of the source sequence.\n * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.\n */\n observableProto.takeLastBuffer = function (count) {\n if (count < 0) { throw new ArgumentOutOfRangeError(); }\n var source = this;\n return new AnonymousObservable(function (o) {\n return source.subscribe(new TakeLastBufferObserver(o, count));\n }, source);\n };\n\n /**\n * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.\n * @param {Number} count Length of each window.\n * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.\n * @returns {Observable} An observable sequence of windows.\n */\n observableProto.windowWithCount = function (count, skip) {\n var source = this;\n +count || (count = 0);\n Math.abs(count) === Infinity && (count = 0);\n if (count <= 0) { throw new ArgumentOutOfRangeError(); }\n skip == null && (skip = count);\n +skip || (skip = 0);\n Math.abs(skip) === Infinity && (skip = 0);\n\n if (skip <= 0) { throw new ArgumentOutOfRangeError(); }\n return new AnonymousObservable(function (observer) {\n var m = new SingleAssignmentDisposable(),\n refCountDisposable = new RefCountDisposable(m),\n n = 0,\n q = [];\n\n function createWindow () {\n var s = new Subject();\n q.push(s);\n observer.onNext(addRef(s, refCountDisposable));\n }\n\n createWindow();\n\n m.setDisposable(source.subscribe(\n function (x) {\n for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }\n var c = n - count + 1;\n c >= 0 && c % skip === 0 && q.shift().onCompleted();\n ++n % skip === 0 && createWindow();\n },\n function (e) {\n while (q.length > 0) { q.shift().onError(e); }\n observer.onError(e);\n },\n function () {\n while (q.length > 0) { q.shift().onCompleted(); }\n observer.onCompleted();\n }\n ));\n return refCountDisposable;\n }, source);\n };\n\n function concatMap(source, selector, thisArg) {\n var selectorFunc = bindCallback(selector, thisArg, 3);\n return source.map(function (x, i) {\n var result = selectorFunc(x, i, source);\n isPromise(result) && (result = observableFromPromise(result));\n (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));\n return result;\n }).concatAll();\n }\n\n /**\n * One of the Following:\n * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.\n *\n * @example\n * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });\n * Or:\n * 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.\n *\n * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });\n * Or:\n * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.\n *\n * var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));\n * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the\n * source sequence onto which could be either an observable or Promise.\n * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.\n * @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.\n */\n observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {\n if (isFunction(selector) && isFunction(resultSelector)) {\n return this.concatMap(function (x, i) {\n var selectorResult = selector(x, i);\n isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));\n (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));\n\n return selectorResult.map(function (y, i2) {\n return resultSelector(x, y, i, i2);\n });\n });\n }\n return isFunction(selector) ?\n concatMap(this, selector, thisArg) :\n concatMap(this, function () { return selector; });\n };\n\n /**\n * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.\n * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.\n * @param {Function} onError A transform function to apply when an error occurs in the source sequence.\n * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.\n * @param {Any} [thisArg] An optional \"this\" to use to invoke each transform.\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.\n */\n observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {\n var source = this,\n onNextFunc = bindCallback(onNext, thisArg, 2),\n onErrorFunc = bindCallback(onError, thisArg, 1),\n onCompletedFunc = bindCallback(onCompleted, thisArg, 0);\n return new AnonymousObservable(function (observer) {\n var index = 0;\n return source.subscribe(\n function (x) {\n var result;\n try {\n result = onNextFunc(x, index++);\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n },\n function (err) {\n var result;\n try {\n result = onErrorFunc(err);\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n observer.onCompleted();\n },\n function () {\n var result;\n try {\n result = onCompletedFunc();\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n observer.onCompleted();\n });\n }, this).concatAll();\n };\n\n var DefaultIfEmptyObserver = (function (__super__) {\n inherits(DefaultIfEmptyObserver, __super__);\n function DefaultIfEmptyObserver(o, d) {\n this._o = o;\n this._d = d;\n this._f = false;\n __super__.call(this);\n }\n\n DefaultIfEmptyObserver.prototype.next = function (x) {\n this._f = true;\n this._o.onNext(x);\n };\n\n DefaultIfEmptyObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n DefaultIfEmptyObserver.prototype.completed = function () {\n !this._f && this._o.onNext(this._d);\n this._o.onCompleted();\n };\n\n return DefaultIfEmptyObserver;\n }(AbstractObserver));\n\n /**\n * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.\n *\n * var res = obs = xs.defaultIfEmpty();\n * 2 - obs = xs.defaultIfEmpty(false);\n *\n * @memberOf Observable#\n * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.\n * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.\n */\n observableProto.defaultIfEmpty = function (defaultValue) {\n var source = this;\n defaultValue === undefined && (defaultValue = null);\n return new AnonymousObservable(function (o) {\n return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));\n }, source);\n };\n\n // Swap out for Array.findIndex\n function arrayIndexOfComparer(array, item, comparer) {\n for (var i = 0, len = array.length; i < len; i++) {\n if (comparer(array[i], item)) { return i; }\n }\n return -1;\n }\n\n function HashSet(comparer) {\n this.comparer = comparer;\n this.set = [];\n }\n HashSet.prototype.push = function(value) {\n var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;\n retValue && this.set.push(value);\n return retValue;\n };\n\n var DistinctObservable = (function (__super__) {\n inherits(DistinctObservable, __super__);\n function DistinctObservable(source, keyFn, cmpFn) {\n this.source = source;\n this._keyFn = keyFn;\n this._cmpFn = cmpFn;\n __super__.call(this);\n }\n\n DistinctObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));\n };\n\n return DistinctObservable;\n }(ObservableBase));\n\n var DistinctObserver = (function (__super__) {\n inherits(DistinctObserver, __super__);\n function DistinctObserver(o, keyFn, cmpFn) {\n this._o = o;\n this._keyFn = keyFn;\n this._h = new HashSet(cmpFn);\n __super__.call(this);\n }\n\n DistinctObserver.prototype.next = function (x) {\n var key = x;\n if (isFunction(this._keyFn)) {\n key = tryCatch(this._keyFn)(x);\n if (key === errorObj) { return this._o.onError(key.e); }\n }\n this._h.push(key) && this._o.onNext(x);\n };\n\n DistinctObserver.prototype.error = function (e) { this._o.onError(e); };\n DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return DistinctObserver;\n }(AbstractObserver));\n\n /**\n * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.\n * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.\n *\n * @example\n * var res = obs = xs.distinct();\n * 2 - obs = xs.distinct(function (x) { return x.id; });\n * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });\n * @param {Function} [keySelector] A function to compute the comparison key for each element.\n * @param {Function} [comparer] Used to compare items in the collection.\n * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.\n */\n observableProto.distinct = function (keySelector, comparer) {\n comparer || (comparer = defaultComparer);\n return new DistinctObservable(this, keySelector, comparer);\n };\n\n /**\n * 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.\n *\n * @example\n * var res = observable.groupBy(function (x) { return x.id; });\n * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });\n * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });\n * @param {Function} keySelector A function to extract the key for each element.\n * @param {Function} [elementSelector] A function to map each source element to an element in an observable group.\n * @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.\n */\n observableProto.groupBy = function (keySelector, elementSelector) {\n return this.groupByUntil(keySelector, elementSelector, observableNever);\n };\n\n /**\n * Groups the elements of an observable sequence according to a specified key selector function.\n * 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\n * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.\n *\n * @example\n * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });\n * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });\n * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });\n * @param {Function} keySelector A function to extract the key for each element.\n * @param {Function} durationSelector A function to signal the expiration of a group.\n * @returns {Observable}\n * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.\n * 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.\n *\n */\n observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) {\n var source = this;\n return new AnonymousObservable(function (o) {\n var map = new Map(),\n groupDisposable = new CompositeDisposable(),\n refCountDisposable = new RefCountDisposable(groupDisposable),\n handleError = function (e) { return function (item) { item.onError(e); }; };\n\n groupDisposable.add(\n source.subscribe(function (x) {\n var key = tryCatch(keySelector)(x);\n if (key === errorObj) {\n map.forEach(handleError(key.e));\n return o.onError(key.e);\n }\n\n var fireNewMapEntry = false, writer = map.get(key);\n if (writer === undefined) {\n writer = new Subject();\n map.set(key, writer);\n fireNewMapEntry = true;\n }\n\n if (fireNewMapEntry) {\n var group = new GroupedObservable(key, writer, refCountDisposable),\n durationGroup = new GroupedObservable(key, writer);\n var duration = tryCatch(durationSelector)(durationGroup);\n if (duration === errorObj) {\n map.forEach(handleError(duration.e));\n return o.onError(duration.e);\n }\n\n o.onNext(group);\n\n var md = new SingleAssignmentDisposable();\n groupDisposable.add(md);\n\n md.setDisposable(duration.take(1).subscribe(\n noop,\n function (e) {\n map.forEach(handleError(e));\n o.onError(e);\n },\n function () {\n if (map['delete'](key)) { writer.onCompleted(); }\n groupDisposable.remove(md);\n }));\n }\n\n var element = x;\n if (isFunction(elementSelector)) {\n element = tryCatch(elementSelector)(x);\n if (element === errorObj) {\n map.forEach(handleError(element.e));\n return o.onError(element.e);\n }\n }\n\n writer.onNext(element);\n }, function (e) {\n map.forEach(handleError(e));\n o.onError(e);\n }, function () {\n map.forEach(function (item) { item.onCompleted(); });\n o.onCompleted();\n }));\n\n return refCountDisposable;\n }, source);\n };\n\n var MapObservable = (function (__super__) {\n inherits(MapObservable, __super__);\n\n function MapObservable(source, selector, thisArg) {\n this.source = source;\n this.selector = bindCallback(selector, thisArg, 3);\n __super__.call(this);\n }\n\n function innerMap(selector, self) {\n return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };\n }\n\n MapObservable.prototype.internalMap = function (selector, thisArg) {\n return new MapObservable(this.source, innerMap(selector, this), thisArg);\n };\n\n MapObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new InnerObserver(o, this.selector, this));\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(o, selector, source) {\n this.o = o;\n this.selector = selector;\n this.source = source;\n this.i = 0;\n AbstractObserver.call(this);\n }\n\n InnerObserver.prototype.next = function(x) {\n var result = tryCatch(this.selector)(x, this.i++, this.source);\n if (result === errorObj) { return this.o.onError(result.e); }\n this.o.onNext(result);\n };\n\n InnerObserver.prototype.error = function (e) {\n this.o.onError(e);\n };\n\n InnerObserver.prototype.completed = function () {\n this.o.onCompleted();\n };\n\n return MapObservable;\n\n }(ObservableBase));\n\n /**\n * Projects each element of an observable sequence into a new form by incorporating the element's index.\n * @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.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.\n */\n observableProto.map = observableProto.select = function (selector, thisArg) {\n var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };\n return this instanceof MapObservable ?\n this.internalMap(selectorFn, thisArg) :\n new MapObservable(this, selectorFn, thisArg);\n };\n\n function plucker(args, len) {\n return function mapper(x) {\n var currentProp = x;\n for (var i = 0; i < len; i++) {\n var p = currentProp[args[i]];\n if (typeof p !== 'undefined') {\n currentProp = p;\n } else {\n return undefined;\n }\n }\n return currentProp;\n }\n }\n\n /**\n * Retrieves the value of a specified nested property from all elements in\n * the Observable sequence.\n * @param {Arguments} arguments The nested properties to pluck.\n * @returns {Observable} Returns a new Observable sequence of property values.\n */\n observableProto.pluck = function () {\n var len = arguments.length, args = new Array(len);\n if (len === 0) { throw new Error('List of properties cannot be empty.'); }\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return this.map(plucker(args, len));\n };\n\nobservableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) {\n return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();\n};\n\n /**\n * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.\n * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.\n * @param {Function} onError A transform function to apply when an error occurs in the source sequence.\n * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.\n * @param {Any} [thisArg] An optional \"this\" to use to invoke each transform.\n * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.\n */\n observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {\n var source = this;\n return new AnonymousObservable(function (observer) {\n var index = 0;\n\n return source.subscribe(\n function (x) {\n var result;\n try {\n result = onNext.call(thisArg, x, index++);\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n },\n function (err) {\n var result;\n try {\n result = onError.call(thisArg, err);\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n observer.onCompleted();\n },\n function () {\n var result;\n try {\n result = onCompleted.call(thisArg);\n } catch (e) {\n observer.onError(e);\n return;\n }\n isPromise(result) && (result = observableFromPromise(result));\n observer.onNext(result);\n observer.onCompleted();\n });\n }, source).mergeAll();\n };\n\nRx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) {\n return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();\n};\n var SkipObservable = (function(__super__) {\n inherits(SkipObservable, __super__);\n function SkipObservable(source, count) {\n this.source = source;\n this._count = count;\n __super__.call(this);\n }\n\n SkipObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SkipObserver(o, this._count));\n };\n\n function SkipObserver(o, c) {\n this._o = o;\n this._r = c;\n AbstractObserver.call(this);\n }\n\n inherits(SkipObserver, AbstractObserver);\n\n SkipObserver.prototype.next = function (x) {\n if (this._r <= 0) {\n this._o.onNext(x);\n } else {\n this._r--;\n }\n };\n SkipObserver.prototype.error = function(e) { this._o.onError(e); };\n SkipObserver.prototype.completed = function() { this._o.onCompleted(); };\n\n return SkipObservable;\n }(ObservableBase));\n\n /**\n * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.\n * @param {Number} count The number of elements to skip before returning the remaining elements.\n * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.\n */\n observableProto.skip = function (count) {\n if (count < 0) { throw new ArgumentOutOfRangeError(); }\n return new SkipObservable(this, count);\n };\n\n var SkipWhileObservable = (function (__super__) {\n inherits(SkipWhileObservable, __super__);\n function SkipWhileObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n SkipWhileObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SkipWhileObserver(o, this));\n };\n\n return SkipWhileObservable;\n }(ObservableBase));\n\n var SkipWhileObserver = (function (__super__) {\n inherits(SkipWhileObserver, __super__);\n\n function SkipWhileObserver(o, p) {\n this._o = o;\n this._p = p;\n this._i = 0;\n this._r = false;\n __super__.call(this);\n }\n\n SkipWhileObserver.prototype.next = function (x) {\n if (!this._r) {\n var res = tryCatch(this._p._fn)(x, this._i++, this._p);\n if (res === errorObj) { return this._o.onError(res.e); }\n this._r = !res;\n }\n this._r && this._o.onNext(x);\n };\n SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };\n SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return SkipWhileObserver;\n }(AbstractObserver));\n\n /**\n * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.\n * The element's index is used in the logic of the predicate function.\n *\n * var res = source.skipWhile(function (value) { return value < 10; });\n * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });\n * @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.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @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.\n */\n observableProto.skipWhile = function (predicate, thisArg) {\n var fn = bindCallback(predicate, thisArg, 3);\n return new SkipWhileObservable(this, fn);\n };\n\n var TakeObservable = (function(__super__) {\n inherits(TakeObservable, __super__);\n function TakeObservable(source, count) {\n this.source = source;\n this._count = count;\n __super__.call(this);\n }\n\n TakeObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new TakeObserver(o, this._count));\n };\n\n function TakeObserver(o, c) {\n this._o = o;\n this._c = c;\n this._r = c;\n AbstractObserver.call(this);\n }\n\n inherits(TakeObserver, AbstractObserver);\n\n TakeObserver.prototype.next = function (x) {\n if (this._r-- > 0) {\n this._o.onNext(x);\n this._r <= 0 && this._o.onCompleted();\n }\n };\n\n TakeObserver.prototype.error = function (e) { this._o.onError(e); };\n TakeObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return TakeObservable;\n }(ObservableBase));\n\n /**\n * 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).\n * @param {Number} count The number of elements to return.\n * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case is set to 0.\n * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.\n */\n observableProto.take = function (count, scheduler) {\n if (count < 0) { throw new ArgumentOutOfRangeError(); }\n if (count === 0) { return observableEmpty(scheduler); }\n return new TakeObservable(this, count);\n };\n\n var TakeWhileObservable = (function (__super__) {\n inherits(TakeWhileObservable, __super__);\n function TakeWhileObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n TakeWhileObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new TakeWhileObserver(o, this));\n };\n\n return TakeWhileObservable;\n }(ObservableBase));\n\n var TakeWhileObserver = (function (__super__) {\n inherits(TakeWhileObserver, __super__);\n\n function TakeWhileObserver(o, p) {\n this._o = o;\n this._p = p;\n this._i = 0;\n this._r = true;\n __super__.call(this);\n }\n\n TakeWhileObserver.prototype.next = function (x) {\n if (this._r) {\n this._r = tryCatch(this._p._fn)(x, this._i++, this._p);\n if (this._r === errorObj) { return this._o.onError(this._r.e); }\n }\n if (this._r) {\n this._o.onNext(x);\n } else {\n this._o.onCompleted();\n }\n };\n TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };\n TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return TakeWhileObserver;\n }(AbstractObserver));\n\n /**\n * Returns elements from an observable sequence as long as a specified condition is true.\n * The element's index is used in the logic of the predicate function.\n * @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.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @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.\n */\n observableProto.takeWhile = function (predicate, thisArg) {\n var fn = bindCallback(predicate, thisArg, 3);\n return new TakeWhileObservable(this, fn);\n };\n\n var FilterObservable = (function (__super__) {\n inherits(FilterObservable, __super__);\n\n function FilterObservable(source, predicate, thisArg) {\n this.source = source;\n this.predicate = bindCallback(predicate, thisArg, 3);\n __super__.call(this);\n }\n\n FilterObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new InnerObserver(o, this.predicate, this));\n };\n\n function innerPredicate(predicate, self) {\n return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }\n }\n\n FilterObservable.prototype.internalFilter = function(predicate, thisArg) {\n return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);\n };\n\n inherits(InnerObserver, AbstractObserver);\n function InnerObserver(o, predicate, source) {\n this.o = o;\n this.predicate = predicate;\n this.source = source;\n this.i = 0;\n AbstractObserver.call(this);\n }\n\n InnerObserver.prototype.next = function(x) {\n var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);\n if (shouldYield === errorObj) {\n return this.o.onError(shouldYield.e);\n }\n shouldYield && this.o.onNext(x);\n };\n\n InnerObserver.prototype.error = function (e) {\n this.o.onError(e);\n };\n\n InnerObserver.prototype.completed = function () {\n this.o.onCompleted();\n };\n\n return FilterObservable;\n\n }(ObservableBase));\n\n /**\n * Filters the elements of an observable sequence based on a predicate by incorporating the element's index.\n * @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.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.\n */\n observableProto.filter = observableProto.where = function (predicate, thisArg) {\n return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :\n new FilterObservable(this, predicate, thisArg);\n };\n\n var ExtremaByObservable = (function (__super__) {\n inherits(ExtremaByObservable, __super__);\n function ExtremaByObservable(source, k, c) {\n this.source = source;\n this._k = k;\n this._c = c;\n __super__.call(this);\n }\n\n ExtremaByObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new ExtremaByObserver(o, this._k, this._c));\n };\n\n return ExtremaByObservable;\n }(ObservableBase));\n\n var ExtremaByObserver = (function (__super__) {\n inherits(ExtremaByObserver, __super__);\n function ExtremaByObserver(o, k, c) {\n this._o = o;\n this._k = k;\n this._c = c;\n this._v = null;\n this._hv = false;\n this._l = [];\n __super__.call(this);\n }\n\n ExtremaByObserver.prototype.next = function (x) {\n var key = tryCatch(this._k)(x);\n if (key === errorObj) { return this._o.onError(key.e); }\n var comparison = 0;\n if (!this._hv) {\n this._hv = true;\n this._v = key;\n } else {\n comparison = tryCatch(this._c)(key, this._v);\n if (comparison === errorObj) { return this._o.onError(comparison.e); }\n }\n if (comparison > 0) {\n this._v = key;\n this._l = [];\n }\n if (comparison >= 0) { this._l.push(x); }\n };\n\n ExtremaByObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ExtremaByObserver.prototype.completed = function () {\n this._o.onNext(this._l);\n this._o.onCompleted();\n };\n\n return ExtremaByObserver;\n }(AbstractObserver));\n\n function firstOnly(x) {\n if (x.length === 0) { throw new EmptyError(); }\n return x[0];\n }\n\n var ReduceObservable = (function(__super__) {\n inherits(ReduceObservable, __super__);\n function ReduceObservable(source, accumulator, hasSeed, seed) {\n this.source = source;\n this.accumulator = accumulator;\n this.hasSeed = hasSeed;\n this.seed = seed;\n __super__.call(this);\n }\n\n ReduceObservable.prototype.subscribeCore = function(observer) {\n return this.source.subscribe(new ReduceObserver(observer,this));\n };\n\n return ReduceObservable;\n }(ObservableBase));\n\n var ReduceObserver = (function (__super__) {\n inherits(ReduceObserver, __super__);\n function ReduceObserver(o, parent) {\n this._o = o;\n this._p = parent;\n this._fn = parent.accumulator;\n this._hs = parent.hasSeed;\n this._s = parent.seed;\n this._ha = false;\n this._a = null;\n this._hv = false;\n this._i = 0;\n __super__.call(this);\n }\n\n ReduceObserver.prototype.next = function (x) {\n !this._hv && (this._hv = true);\n if (this._ha) {\n this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);\n } else {\n this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;\n this._ha = true;\n }\n if (this._a === errorObj) { return this._o.onError(this._a.e); }\n this._i++;\n };\n\n ReduceObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ReduceObserver.prototype.completed = function () {\n this._hv && this._o.onNext(this._a);\n !this._hv && this._hs && this._o.onNext(this._s);\n !this._hv && !this._hs && this._o.onError(new EmptyError());\n this._o.onCompleted();\n };\n\n return ReduceObserver;\n }(AbstractObserver));\n\n /**\n * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.\n * For aggregation behavior with incremental intermediate results, see Observable.scan.\n * @param {Function} accumulator An accumulator function to be invoked on each element.\n * @param {Any} [seed] The initial accumulator value.\n * @returns {Observable} An observable sequence containing a single element with the final accumulator value.\n */\n observableProto.reduce = function () {\n var hasSeed = false, seed, accumulator = arguments[0];\n if (arguments.length === 2) {\n hasSeed = true;\n seed = arguments[1];\n }\n return new ReduceObservable(this, accumulator, hasSeed, seed);\n };\n\n var SomeObservable = (function (__super__) {\n inherits(SomeObservable, __super__);\n function SomeObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n SomeObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SomeObserver(o, this._fn, this.source));\n };\n\n return SomeObservable;\n }(ObservableBase));\n\n var SomeObserver = (function (__super__) {\n inherits(SomeObserver, __super__);\n\n function SomeObserver(o, fn, s) {\n this._o = o;\n this._fn = fn;\n this._s = s;\n this._i = 0;\n __super__.call(this);\n }\n\n SomeObserver.prototype.next = function (x) {\n var result = tryCatch(this._fn)(x, this._i++, this._s);\n if (result === errorObj) { return this._o.onError(result.e); }\n if (Boolean(result)) {\n this._o.onNext(true);\n this._o.onCompleted();\n }\n };\n SomeObserver.prototype.error = function (e) { this._o.onError(e); };\n SomeObserver.prototype.completed = function () {\n this._o.onNext(false);\n this._o.onCompleted();\n };\n\n return SomeObserver;\n }(AbstractObserver));\n\n /**\n * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.\n * @param {Function} [predicate] A function to test each element for a condition.\n * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.\n */\n observableProto.some = function (predicate, thisArg) {\n var fn = bindCallback(predicate, thisArg, 3);\n return new SomeObservable(this, fn);\n };\n\n var IsEmptyObservable = (function (__super__) {\n inherits(IsEmptyObservable, __super__);\n function IsEmptyObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n IsEmptyObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new IsEmptyObserver(o));\n };\n\n return IsEmptyObservable;\n }(ObservableBase));\n\n var IsEmptyObserver = (function(__super__) {\n inherits(IsEmptyObserver, __super__);\n function IsEmptyObserver(o) {\n this._o = o;\n __super__.call(this);\n }\n\n IsEmptyObserver.prototype.next = function () {\n this._o.onNext(false);\n this._o.onCompleted();\n };\n IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); };\n IsEmptyObserver.prototype.completed = function () {\n this._o.onNext(true);\n this._o.onCompleted();\n };\n\n return IsEmptyObserver;\n }(AbstractObserver));\n\n /**\n * Determines whether an observable sequence is empty.\n * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.\n */\n observableProto.isEmpty = function () {\n return new IsEmptyObservable(this);\n };\n\n var EveryObservable = (function (__super__) {\n inherits(EveryObservable, __super__);\n function EveryObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n EveryObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new EveryObserver(o, this._fn, this.source));\n };\n\n return EveryObservable;\n }(ObservableBase));\n\n var EveryObserver = (function (__super__) {\n inherits(EveryObserver, __super__);\n\n function EveryObserver(o, fn, s) {\n this._o = o;\n this._fn = fn;\n this._s = s;\n this._i = 0;\n __super__.call(this);\n }\n\n EveryObserver.prototype.next = function (x) {\n var result = tryCatch(this._fn)(x, this._i++, this._s);\n if (result === errorObj) { return this._o.onError(result.e); }\n if (!Boolean(result)) {\n this._o.onNext(false);\n this._o.onCompleted();\n }\n };\n EveryObserver.prototype.error = function (e) { this._o.onError(e); };\n EveryObserver.prototype.completed = function () {\n this._o.onNext(true);\n this._o.onCompleted();\n };\n\n return EveryObserver;\n }(AbstractObserver));\n\n /**\n * Determines whether all elements of an observable sequence satisfy a condition.\n * @param {Function} [predicate] A function to test each element for a condition.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.\n */\n observableProto.every = function (predicate, thisArg) {\n var fn = bindCallback(predicate, thisArg, 3);\n return new EveryObservable(this, fn);\n };\n\n var IncludesObservable = (function (__super__) {\n inherits(IncludesObservable, __super__);\n function IncludesObservable(source, elem, idx) {\n var n = +idx || 0;\n Math.abs(n) === Infinity && (n = 0);\n\n this.source = source;\n this._elem = elem;\n this._n = n;\n __super__.call(this);\n }\n\n IncludesObservable.prototype.subscribeCore = function (o) {\n if (this._n < 0) {\n o.onNext(false);\n o.onCompleted();\n return disposableEmpty;\n }\n\n return this.source.subscribe(new IncludesObserver(o, this._elem, this._n));\n };\n\n return IncludesObservable;\n }(ObservableBase));\n\n var IncludesObserver = (function (__super__) {\n inherits(IncludesObserver, __super__);\n function IncludesObserver(o, elem, n) {\n this._o = o;\n this._elem = elem;\n this._n = n;\n this._i = 0;\n __super__.call(this);\n }\n\n function comparer(a, b) {\n return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));\n }\n\n IncludesObserver.prototype.next = function (x) {\n if (this._i++ >= this._n && comparer(x, this._elem)) {\n this._o.onNext(true);\n this._o.onCompleted();\n }\n };\n IncludesObserver.prototype.error = function (e) { this._o.onError(e); };\n IncludesObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); };\n\n return IncludesObserver;\n }(AbstractObserver));\n\n /**\n * Determines whether an observable sequence includes a specified element with an optional equality comparer.\n * @param searchElement The value to locate in the source sequence.\n * @param {Number} [fromIndex] An equality comparer to compare elements.\n * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.\n */\n observableProto.includes = function (searchElement, fromIndex) {\n return new IncludesObservable(this, searchElement, fromIndex);\n };\n\n var CountObservable = (function (__super__) {\n inherits(CountObservable, __super__);\n function CountObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n CountObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new CountObserver(o, this._fn, this.source));\n };\n\n return CountObservable;\n }(ObservableBase));\n\n var CountObserver = (function (__super__) {\n inherits(CountObserver, __super__);\n\n function CountObserver(o, fn, s) {\n this._o = o;\n this._fn = fn;\n this._s = s;\n this._i = 0;\n this._c = 0;\n __super__.call(this);\n }\n\n CountObserver.prototype.next = function (x) {\n if (this._fn) {\n var result = tryCatch(this._fn)(x, this._i++, this._s);\n if (result === errorObj) { return this._o.onError(result.e); }\n Boolean(result) && (this._c++);\n } else {\n this._c++;\n }\n };\n CountObserver.prototype.error = function (e) { this._o.onError(e); };\n CountObserver.prototype.completed = function () {\n this._o.onNext(this._c);\n this._o.onCompleted();\n };\n\n return CountObserver;\n }(AbstractObserver));\n\n /**\n * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.\n * @example\n * res = source.count();\n * res = source.count(function (x) { return x > 3; });\n * @param {Function} [predicate]A function to test each element for a condition.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.\n */\n observableProto.count = function (predicate, thisArg) {\n var fn = bindCallback(predicate, thisArg, 3);\n return new CountObservable(this, fn);\n };\n\n var IndexOfObservable = (function (__super__) {\n inherits(IndexOfObservable, __super__);\n function IndexOfObservable(source, e, n) {\n this.source = source;\n this._e = e;\n this._n = n;\n __super__.call(this);\n }\n\n IndexOfObservable.prototype.subscribeCore = function (o) {\n if (this._n < 0) {\n o.onNext(-1);\n o.onCompleted();\n return disposableEmpty;\n }\n\n return this.source.subscribe(new IndexOfObserver(o, this._e, this._n));\n };\n\n return IndexOfObservable;\n }(ObservableBase));\n\n var IndexOfObserver = (function (__super__) {\n inherits(IndexOfObserver, __super__);\n function IndexOfObserver(o, e, n) {\n this._o = o;\n this._e = e;\n this._n = n;\n this._i = 0;\n __super__.call(this);\n }\n\n IndexOfObserver.prototype.next = function (x) {\n if (this._i >= this._n && x === this._e) {\n this._o.onNext(this._i);\n this._o.onCompleted();\n }\n this._i++;\n };\n IndexOfObserver.prototype.error = function (e) { this._o.onError(e); };\n IndexOfObserver.prototype.completed = function () { this._o.onNext(-1); this._o.onCompleted(); };\n\n return IndexOfObserver;\n }(AbstractObserver));\n\n /**\n * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.\n * @param {Any} searchElement Element to locate in the array.\n * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.\n * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.\n */\n observableProto.indexOf = function(searchElement, fromIndex) {\n var n = +fromIndex || 0;\n Math.abs(n) === Infinity && (n = 0);\n return new IndexOfObservable(this, searchElement, n);\n };\n\n var SumObservable = (function (__super__) {\n inherits(SumObservable, __super__);\n function SumObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n SumObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SumObserver(o, this._fn, this.source));\n };\n\n return SumObservable;\n }(ObservableBase));\n\n var SumObserver = (function (__super__) {\n inherits(SumObserver, __super__);\n\n function SumObserver(o, fn, s) {\n this._o = o;\n this._fn = fn;\n this._s = s;\n this._i = 0;\n this._c = 0;\n __super__.call(this);\n }\n\n SumObserver.prototype.next = function (x) {\n if (this._fn) {\n var result = tryCatch(this._fn)(x, this._i++, this._s);\n if (result === errorObj) { return this._o.onError(result.e); }\n this._c += result;\n } else {\n this._c += x;\n }\n };\n SumObserver.prototype.error = function (e) { this._o.onError(e); };\n SumObserver.prototype.completed = function () {\n this._o.onNext(this._c);\n this._o.onCompleted();\n };\n\n return SumObserver;\n }(AbstractObserver));\n\n /**\n * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.\n * @param {Function} [selector] A transform function to apply to each element.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.\n */\n observableProto.sum = function (keySelector, thisArg) {\n var fn = bindCallback(keySelector, thisArg, 3);\n return new SumObservable(this, fn);\n };\n\n /**\n * Returns the elements in an observable sequence with the minimum key value according to the specified comparer.\n * @example\n * var res = source.minBy(function (x) { return x.value; });\n * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });\n * @param {Function} keySelector Key selector function.\n * @param {Function} [comparer] Comparer used to compare key values.\n * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.\n */\n observableProto.minBy = function (keySelector, comparer) {\n comparer || (comparer = defaultSubComparer);\n return new ExtremaByObservable(this, keySelector, function (x, y) { return comparer(x, y) * -1; });\n };\n\n /**\n * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.\n * @example\n * var res = source.min();\n * var res = source.min(function (x, y) { return x.value - y.value; });\n * @param {Function} [comparer] Comparer used to compare elements.\n * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.\n */\n observableProto.min = function (comparer) {\n return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });\n };\n\n /**\n * Returns the elements in an observable sequence with the maximum key value according to the specified comparer.\n * @example\n * var res = source.maxBy(function (x) { return x.value; });\n * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });\n * @param {Function} keySelector Key selector function.\n * @param {Function} [comparer] Comparer used to compare key values.\n * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.\n */\n observableProto.maxBy = function (keySelector, comparer) {\n comparer || (comparer = defaultSubComparer);\n return new ExtremaByObservable(this, keySelector, comparer);\n };\n\n /**\n * Returns the maximum value in an observable sequence according to the specified comparer.\n * @example\n * var res = source.max();\n * var res = source.max(function (x, y) { return x.value - y.value; });\n * @param {Function} [comparer] Comparer used to compare elements.\n * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.\n */\n observableProto.max = function (comparer) {\n return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });\n };\n\n var AverageObservable = (function (__super__) {\n inherits(AverageObservable, __super__);\n function AverageObservable(source, fn) {\n this.source = source;\n this._fn = fn;\n __super__.call(this);\n }\n\n AverageObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new AverageObserver(o, this._fn, this.source));\n };\n\n return AverageObservable;\n }(ObservableBase));\n\n var AverageObserver = (function(__super__) {\n inherits(AverageObserver, __super__);\n function AverageObserver(o, fn, s) {\n this._o = o;\n this._fn = fn;\n this._s = s;\n this._c = 0;\n this._t = 0;\n __super__.call(this);\n }\n\n AverageObserver.prototype.next = function (x) {\n if(this._fn) {\n var r = tryCatch(this._fn)(x, this._c++, this._s);\n if (r === errorObj) { return this._o.onError(r.e); }\n this._t += r;\n } else {\n this._c++;\n this._t += x;\n }\n };\n AverageObserver.prototype.error = function (e) { this._o.onError(e); };\n AverageObserver.prototype.completed = function () {\n if (this._c === 0) { return this._o.onError(new EmptyError()); }\n this._o.onNext(this._t / this._c);\n this._o.onCompleted();\n };\n\n return AverageObserver;\n }(AbstractObserver));\n\n /**\n * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.\n * @param {Function} [selector] A transform function to apply to each element.\n * @param {Any} [thisArg] Object to use as this when executing callback.\n * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.\n */\n observableProto.average = function (keySelector, thisArg) {\n var source = this, fn;\n if (isFunction(keySelector)) {\n fn = bindCallback(keySelector, thisArg, 3);\n }\n return new AverageObservable(source, fn);\n };\n\n /**\n * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.\n *\n * @example\n * var res = res = source.sequenceEqual([1,2,3]);\n * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });\n * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));\n * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });\n * @param {Observable} second Second observable sequence or array to compare.\n * @param {Function} [comparer] Comparer used to compare elements of both sequences.\n * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.\n */\n observableProto.sequenceEqual = function (second, comparer) {\n var first = this;\n comparer || (comparer = defaultComparer);\n return new AnonymousObservable(function (o) {\n var donel = false, doner = false, ql = [], qr = [];\n var subscription1 = first.subscribe(function (x) {\n if (qr.length > 0) {\n var v = qr.shift();\n var equal = tryCatch(comparer)(v, x);\n if (equal === errorObj) { return o.onError(equal.e); }\n if (!equal) {\n o.onNext(false);\n o.onCompleted();\n }\n } else if (doner) {\n o.onNext(false);\n o.onCompleted();\n } else {\n ql.push(x);\n }\n }, function(e) { o.onError(e); }, function () {\n donel = true;\n if (ql.length === 0) {\n if (qr.length > 0) {\n o.onNext(false);\n o.onCompleted();\n } else if (doner) {\n o.onNext(true);\n o.onCompleted();\n }\n }\n });\n\n (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));\n isPromise(second) && (second = observableFromPromise(second));\n var subscription2 = second.subscribe(function (x) {\n if (ql.length > 0) {\n var v = ql.shift();\n var equal = tryCatch(comparer)(v, x);\n if (equal === errorObj) { return o.onError(equal.e); }\n if (!equal) {\n o.onNext(false);\n o.onCompleted();\n }\n } else if (donel) {\n o.onNext(false);\n o.onCompleted();\n } else {\n qr.push(x);\n }\n }, function(e) { o.onError(e); }, function () {\n doner = true;\n if (qr.length === 0) {\n if (ql.length > 0) {\n o.onNext(false);\n o.onCompleted();\n } else if (donel) {\n o.onNext(true);\n o.onCompleted();\n }\n }\n });\n return new BinaryDisposable(subscription1, subscription2);\n }, first);\n };\n\n var ElementAtObservable = (function (__super__) {\n inherits(ElementAtObservable, __super__);\n function ElementAtObservable(source, i, d) {\n this.source = source;\n this._i = i;\n this._d = d;\n __super__.call(this);\n }\n\n ElementAtObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new ElementAtObserver(o, this._i, this._d));\n };\n\n return ElementAtObservable;\n }(ObservableBase));\n\n var ElementAtObserver = (function (__super__) {\n inherits(ElementAtObserver, __super__);\n\n function ElementAtObserver(o, i, d) {\n this._o = o;\n this._i = i;\n this._d = d;\n __super__.call(this);\n }\n\n ElementAtObserver.prototype.next = function (x) {\n if (this._i-- === 0) {\n this._o.onNext(x);\n this._o.onCompleted();\n }\n };\n ElementAtObserver.prototype.error = function (e) { this._o.onError(e); };\n ElementAtObserver.prototype.completed = function () {\n if (this._d === undefined) {\n this._o.onError(new ArgumentOutOfRangeError());\n } else {\n this._o.onNext(this._d);\n this._o.onCompleted();\n }\n };\n\n return ElementAtObserver;\n }(AbstractObserver));\n\n /**\n * Returns the element at a specified index in a sequence or default value if not found.\n * @param {Number} index The zero-based index of the element to retrieve.\n * @param {Any} [defaultValue] The default value to use if elementAt does not find a value.\n * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.\n */\n observableProto.elementAt = function (index, defaultValue) {\n if (index < 0) { throw new ArgumentOutOfRangeError(); }\n return new ElementAtObservable(this, index, defaultValue);\n };\n\n var SingleObserver = (function(__super__) {\n inherits(SingleObserver, __super__);\n function SingleObserver(o, obj, s) {\n this._o = o;\n this._obj = obj;\n this._s = s;\n this._i = 0;\n this._hv = false;\n this._v = null;\n __super__.call(this);\n }\n\n SingleObserver.prototype.next = function (x) {\n var shouldYield = false;\n if (this._obj.predicate) {\n var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);\n if (res === errorObj) { return this._o.onError(res.e); }\n Boolean(res) && (shouldYield = true);\n } else if (!this._obj.predicate) {\n shouldYield = true;\n }\n if (shouldYield) {\n if (this._hv) {\n return this._o.onError(new Error('Sequence contains more than one matching element'));\n }\n this._hv = true;\n this._v = x;\n }\n };\n SingleObserver.prototype.error = function (e) { this._o.onError(e); };\n SingleObserver.prototype.completed = function () {\n if (this._hv) {\n this._o.onNext(this._v);\n this._o.onCompleted();\n }\n else if (this._obj.defaultValue === undefined) {\n this._o.onError(new EmptyError());\n } else {\n this._o.onNext(this._obj.defaultValue);\n this._o.onCompleted();\n }\n };\n\n return SingleObserver;\n }(AbstractObserver));\n\n\n /**\n * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.\n * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.\n */\n observableProto.single = function (predicate, thisArg) {\n var obj = {}, source = this;\n if (typeof arguments[0] === 'object') {\n obj = arguments[0];\n } else {\n obj = {\n predicate: arguments[0],\n thisArg: arguments[1],\n defaultValue: arguments[2]\n };\n }\n if (isFunction (obj.predicate)) {\n var fn = obj.predicate;\n obj.predicate = bindCallback(fn, obj.thisArg, 3);\n }\n return new AnonymousObservable(function (o) {\n return source.subscribe(new SingleObserver(o, obj, source));\n }, source);\n };\n\n var FirstObservable = (function (__super__) {\n inherits(FirstObservable, __super__);\n function FirstObservable(source, obj) {\n this.source = source;\n this._obj = obj;\n __super__.call(this);\n }\n\n FirstObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new FirstObserver(o, this._obj, this.source));\n };\n\n return FirstObservable;\n }(ObservableBase));\n\n var FirstObserver = (function(__super__) {\n inherits(FirstObserver, __super__);\n function FirstObserver(o, obj, s) {\n this._o = o;\n this._obj = obj;\n this._s = s;\n this._i = 0;\n __super__.call(this);\n }\n\n FirstObserver.prototype.next = function (x) {\n if (this._obj.predicate) {\n var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);\n if (res === errorObj) { return this._o.onError(res.e); }\n if (Boolean(res)) {\n this._o.onNext(x);\n this._o.onCompleted();\n }\n } else if (!this._obj.predicate) {\n this._o.onNext(x);\n this._o.onCompleted();\n }\n };\n FirstObserver.prototype.error = function (e) { this._o.onError(e); };\n FirstObserver.prototype.completed = function () {\n if (this._obj.defaultValue === undefined) {\n this._o.onError(new EmptyError());\n } else {\n this._o.onNext(this._obj.defaultValue);\n this._o.onCompleted();\n }\n };\n\n return FirstObserver;\n }(AbstractObserver));\n\n /**\n * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.\n * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.\n */\n observableProto.first = function () {\n var obj = {}, source = this;\n if (typeof arguments[0] === 'object') {\n obj = arguments[0];\n } else {\n obj = {\n predicate: arguments[0],\n thisArg: arguments[1],\n defaultValue: arguments[2]\n };\n }\n if (isFunction (obj.predicate)) {\n var fn = obj.predicate;\n obj.predicate = bindCallback(fn, obj.thisArg, 3);\n }\n return new FirstObservable(this, obj);\n };\n\n var LastObservable = (function (__super__) {\n inherits(LastObservable, __super__);\n function LastObservable(source, obj) {\n this.source = source;\n this._obj = obj;\n __super__.call(this);\n }\n\n LastObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new LastObserver(o, this._obj, this.source));\n };\n\n return LastObservable;\n }(ObservableBase));\n\n var LastObserver = (function(__super__) {\n inherits(LastObserver, __super__);\n function LastObserver(o, obj, s) {\n this._o = o;\n this._obj = obj;\n this._s = s;\n this._i = 0;\n this._hv = false;\n this._v = null;\n __super__.call(this);\n }\n\n LastObserver.prototype.next = function (x) {\n var shouldYield = false;\n if (this._obj.predicate) {\n var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);\n if (res === errorObj) { return this._o.onError(res.e); }\n Boolean(res) && (shouldYield = true);\n } else if (!this._obj.predicate) {\n shouldYield = true;\n }\n if (shouldYield) {\n this._hv = true;\n this._v = x;\n }\n };\n LastObserver.prototype.error = function (e) { this._o.onError(e); };\n LastObserver.prototype.completed = function () {\n if (this._hv) {\n this._o.onNext(this._v);\n this._o.onCompleted();\n }\n else if (this._obj.defaultValue === undefined) {\n this._o.onError(new EmptyError());\n } else {\n this._o.onNext(this._obj.defaultValue);\n this._o.onCompleted();\n }\n };\n\n return LastObserver;\n }(AbstractObserver));\n\n /**\n * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.\n * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.\n */\n observableProto.last = function () {\n var obj = {}, source = this;\n if (typeof arguments[0] === 'object') {\n obj = arguments[0];\n } else {\n obj = {\n predicate: arguments[0],\n thisArg: arguments[1],\n defaultValue: arguments[2]\n };\n }\n if (isFunction (obj.predicate)) {\n var fn = obj.predicate;\n obj.predicate = bindCallback(fn, obj.thisArg, 3);\n }\n return new LastObservable(this, obj);\n };\n\n var FindValueObserver = (function(__super__) {\n inherits(FindValueObserver, __super__);\n function FindValueObserver(observer, source, callback, yieldIndex) {\n this._o = observer;\n this._s = source;\n this._cb = callback;\n this._y = yieldIndex;\n this._i = 0;\n __super__.call(this);\n }\n\n FindValueObserver.prototype.next = function (x) {\n var shouldRun = tryCatch(this._cb)(x, this._i, this._s);\n if (shouldRun === errorObj) { return this._o.onError(shouldRun.e); }\n if (shouldRun) {\n this._o.onNext(this._y ? this._i : x);\n this._o.onCompleted();\n } else {\n this._i++;\n }\n };\n\n FindValueObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n FindValueObserver.prototype.completed = function () {\n this._y && this._o.onNext(-1);\n this._o.onCompleted();\n };\n\n return FindValueObserver;\n }(AbstractObserver));\n\n function findValue (source, predicate, thisArg, yieldIndex) {\n var callback = bindCallback(predicate, thisArg, 3);\n return new AnonymousObservable(function (o) {\n return source.subscribe(new FindValueObserver(o, source, callback, yieldIndex));\n }, source);\n }\n\n /**\n * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.\n * @param {Function} predicate The predicate that defines the conditions of the element to search for.\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate.\n * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.\n */\n observableProto.find = function (predicate, thisArg) {\n return findValue(this, predicate, thisArg, false);\n };\n\n /**\n * Searches for an element that matches the conditions defined by the specified predicate, and returns\n * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.\n * @param {Function} predicate The predicate that defines the conditions of the element to search for.\n * @param {Any} [thisArg] Object to use as `this` when executing the predicate.\n * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.\n */\n observableProto.findIndex = function (predicate, thisArg) {\n return findValue(this, predicate, thisArg, true);\n };\n\n var ToSetObservable = (function (__super__) {\n inherits(ToSetObservable, __super__);\n function ToSetObservable(source) {\n this.source = source;\n __super__.call(this);\n }\n\n ToSetObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new ToSetObserver(o));\n };\n\n return ToSetObservable;\n }(ObservableBase));\n\n var ToSetObserver = (function (__super__) {\n inherits(ToSetObserver, __super__);\n function ToSetObserver(o) {\n this._o = o;\n this._s = new root.Set();\n __super__.call(this);\n }\n\n ToSetObserver.prototype.next = function (x) {\n this._s.add(x);\n };\n\n ToSetObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ToSetObserver.prototype.completed = function () {\n this._o.onNext(this._s);\n this._o.onCompleted();\n };\n\n return ToSetObserver;\n }(AbstractObserver));\n\n /**\n * Converts the observable sequence to a Set if it exists.\n * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.\n */\n observableProto.toSet = function () {\n if (typeof root.Set === 'undefined') { throw new TypeError(); }\n return new ToSetObservable(this);\n };\n\n var ToMapObservable = (function (__super__) {\n inherits(ToMapObservable, __super__);\n function ToMapObservable(source, k, e) {\n this.source = source;\n this._k = k;\n this._e = e;\n __super__.call(this);\n }\n\n ToMapObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new ToMapObserver(o, this._k, this._e));\n };\n\n return ToMapObservable;\n }(ObservableBase));\n\n var ToMapObserver = (function (__super__) {\n inherits(ToMapObserver, __super__);\n function ToMapObserver(o, k, e) {\n this._o = o;\n this._k = k;\n this._e = e;\n this._m = new root.Map();\n __super__.call(this);\n }\n\n ToMapObserver.prototype.next = function (x) {\n var key = tryCatch(this._k)(x);\n if (key === errorObj) { return this._o.onError(key.e); }\n var elem = x;\n if (this._e) {\n elem = tryCatch(this._e)(x);\n if (elem === errorObj) { return this._o.onError(elem.e); }\n }\n\n this._m.set(key, elem);\n };\n\n ToMapObserver.prototype.error = function (e) {\n this._o.onError(e);\n };\n\n ToMapObserver.prototype.completed = function () {\n this._o.onNext(this._m);\n this._o.onCompleted();\n };\n\n return ToMapObserver;\n }(AbstractObserver));\n\n /**\n * Converts the observable sequence to a Map if it exists.\n * @param {Function} keySelector A function which produces the key for the Map.\n * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.\n * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.\n */\n observableProto.toMap = function (keySelector, elementSelector) {\n if (typeof root.Map === 'undefined') { throw new TypeError(); }\n return new ToMapObservable(this, keySelector, elementSelector);\n };\n\n var SliceObservable = (function (__super__) {\n inherits(SliceObservable, __super__);\n function SliceObservable(source, b, e) {\n this.source = source;\n this._b = b;\n this._e = e;\n __super__.call(this);\n }\n\n SliceObservable.prototype.subscribeCore = function (o) {\n return this.source.subscribe(new SliceObserver(o, this._b, this._e));\n };\n\n return SliceObservable;\n }(ObservableBase));\n\n var SliceObserver = (function (__super__) {\n inherits(SliceObserver, __super__);\n\n function SliceObserver(o, b, e) {\n this._o = o;\n this._b = b;\n this._e = e;\n this._i = 0;\n __super__.call(this);\n }\n\n SliceObserver.prototype.next = function (x) {\n if (this._i >= this._b) {\n if (this._e === this._i) {\n this._o.onCompleted();\n } else {\n this._o.onNext(x);\n }\n }\n this._i++;\n };\n SliceObserver.prototype.error = function (e) { this._o.onError(e); };\n SliceObserver.prototype.completed = function () { this._o.onCompleted(); };\n\n return SliceObserver;\n }(AbstractObserver));\n\n /*\n * The slice() method returns a shallow copy of a portion of an Observable into a new Observable object.\n * Unlike the array version, this does not support negative numbers for being or end.\n * @param {Number} [begin] Zero-based index at which to begin extraction. If omitted, this will default to zero.\n * @param {Number} [end] Zero-based index at which to end extraction. slice extracts up to but not including end.\n * If omitted, this will emit the rest of the Observable object.\n * @returns {Observable} A shallow copy of a portion of an Observable into a new Observable object.\n */\n observableProto.slice = function (begin, end) {\n var start = begin || 0;\n if (start < 0) { throw new Rx.ArgumentOutOfRangeError(); }\n if (typeof end === 'number' && end < start) {\n throw new Rx.ArgumentOutOfRangeError();\n }\n return new SliceObservable(this, start, end);\n };\n\n var LastIndexOfObservable = (function (__super__) {\n inherits(LastIndexOfObservable, __super__);\n function LastIndexOfObservable(source, e, n) {\n this.source = source;\n this._e = e;\n this._n = n;\n __super__.call(this);\n }\n\n LastIndexOfObservable.prototype.subscribeCore = function (o) {\n if (this._n < 0) {\n o.onNext(-1);\n o.onCompleted();\n return disposableEmpty;\n }\n\n return this.source.subscribe(new LastIndexOfObserver(o, this._e, this._n));\n };\n\n return LastIndexOfObservable;\n }(ObservableBase));\n\n var LastIndexOfObserver = (function (__super__) {\n inherits(LastIndexOfObserver, __super__);\n function LastIndexOfObserver(o, e, n) {\n this._o = o;\n this._e = e;\n this._n = n;\n this._v = 0;\n this._hv = false;\n this._i = 0;\n __super__.call(this);\n }\n\n LastIndexOfObserver.prototype.next = function (x) {\n if (this._i >= this._n && x === this._e) {\n this._hv = true;\n this._v = this._i;\n }\n this._i++;\n };\n LastIndexOfObserver.prototype.error = function (e) { this._o.onError(e); };\n LastIndexOfObserver.prototype.completed = function () {\n if (this._hv) {\n this._o.onNext(this._v);\n } else {\n this._o.onNext(-1);\n }\n this._o.onCompleted();\n };\n\n return LastIndexOfObserver;\n }(AbstractObserver));\n\n /**\n * Returns the last index at which a given element can be found in the observable sequence, or -1 if it is not present.\n * @param {Any} searchElement Element to locate in the array.\n * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.\n * @returns {Observable} And observable sequence containing the last index at which a given element can be found in the observable sequence, or -1 if it is not present.\n */\n observableProto.lastIndexOf = function(searchElement, fromIndex) {\n var n = +fromIndex || 0;\n Math.abs(n) === Infinity && (n = 0);\n return new LastIndexOfObservable(this, searchElement, n);\n };\n\n Observable.wrap = function (fn) {\n function createObservable() {\n return Observable.spawn.call(this, fn.apply(this, arguments));\n }\n\n createObservable.__generatorFunction__ = fn;\n return createObservable;\n };\n\n var spawn = Observable.spawn = function () {\n var gen = arguments[0], self = this, args = [];\n for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }\n\n return new AnonymousObservable(function (o) {\n var g = new CompositeDisposable();\n\n if (isFunction(gen)) { gen = gen.apply(self, args); }\n if (!gen || !isFunction(gen.next)) {\n o.onNext(gen);\n return o.onCompleted();\n }\n\n function processGenerator(res) {\n var ret = tryCatch(gen.next).call(gen, res);\n if (ret === errorObj) { return o.onError(ret.e); }\n next(ret);\n }\n\n processGenerator();\n\n function onError(err) {\n var ret = tryCatch(gen.next).call(gen, err);\n if (ret === errorObj) { return o.onError(ret.e); }\n next(ret);\n }\n\n function next(ret) {\n if (ret.done) {\n o.onNext(ret.value);\n o.onCompleted();\n return;\n }\n var obs = toObservable.call(self, ret.value);\n var value = null;\n var hasValue = false;\n if (Observable.isObservable(obs)) {\n g.add(obs.subscribe(function(val) {\n hasValue = true;\n value = val;\n }, onError, function() {\n hasValue && processGenerator(value);\n }));\n } else {\n onError(new TypeError('type not supported'));\n }\n }\n\n return g;\n });\n };\n\n function toObservable(obj) {\n if (!obj) { return obj; }\n if (Observable.isObservable(obj)) { return obj; }\n if (isPromise(obj)) { return Observable.fromPromise(obj); }\n if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); }\n if (isFunction(obj)) { return thunkToObservable.call(this, obj); }\n if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); }\n if (isObject(obj)) {return objectToObservable.call(this, obj);}\n return obj;\n }\n\n function arrayToObservable (obj) {\n return Observable.from(obj).concatMap(function(o) {\n if(Observable.isObservable(o) || isObject(o)) {\n return toObservable.call(null, o);\n } else {\n return Rx.Observable.just(o);\n }\n }).toArray();\n }\n\n function objectToObservable (obj) {\n var results = new obj.constructor(), keys = Object.keys(obj), observables = [];\n for (var i = 0, len = keys.length; i < len; i++) {\n var key = keys[i];\n var observable = toObservable.call(this, obj[key]);\n\n if(observable && Observable.isObservable(observable)) {\n defer(observable, key);\n } else {\n results[key] = obj[key];\n }\n }\n\n return Observable.forkJoin.apply(Observable, observables).map(function() {\n return results;\n });\n\n\n function defer (observable, key) {\n results[key] = undefined;\n observables.push(observable.map(function (next) {\n results[key] = next;\n }));\n }\n }\n\n function thunkToObservable(fn) {\n var self = this;\n return new AnonymousObservable(function (o) {\n fn.call(self, function () {\n var err = arguments[0], res = arguments[1];\n if (err) { return o.onError(err); }\n if (arguments.length > 2) {\n var args = [];\n for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }\n res = args;\n }\n o.onNext(res);\n o.onCompleted();\n });\n });\n }\n\n function isGenerator(obj) {\n return isFunction (obj.next) && isFunction (obj['throw']);\n }\n\n function isGeneratorFunction(obj) {\n var ctor = obj.constructor;\n if (!ctor) { return false; }\n if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; }\n return isGenerator(ctor.prototype);\n }\n\n function isObject(val) {\n return Object == val.constructor;\n }\n\n /**\n * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.\n *\n * @example\n * var res = Rx.Observable.start(function () { console.log('hello'); });\n * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);\n * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);\n *\n * @param {Function} func Function to run asynchronously.\n * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.\n * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\n * @returns {Observable} An observable sequence exposing the function's result value, or an exception.\n *\n * Remarks\n * * The function is called immediately, not during the subscription of the resulting sequence.\n * * Multiple subscriptions to the resulting sequence can observe the function's result.\n */\n Observable.start = function (func, context, scheduler) {\n return observableToAsync(func, context, scheduler)();\n };\n\n /**\n * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.\n * @param {Function} function Function to convert to an asynchronous function.\n * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.\n * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.\n * @returns {Function} Asynchronous function.\n */\n var observableToAsync = Observable.toAsync = function (func, context, scheduler) {\n isScheduler(scheduler) || (scheduler = defaultScheduler);\n return function () {\n var args = arguments,\n subject = new AsyncSubject();\n\n scheduler.schedule(null, function () {\n var result;\n try {\n result = func.apply(context, args);\n } catch (e) {\n subject.onError(e);\n return;\n }\n subject.onNext(result);\n subject.onCompleted();\n });\n return subject.asObservable();\n };\n };\n\nfunction createCbObservable(fn, ctx, selector, args) {\n var o = new AsyncSubject();\n\n args.push(createCbHandler(o, ctx, selector));\n fn.apply(ctx, args);\n\n return o.asObservable();\n}\n\nfunction createCbHandler(o, ctx, selector) {\n return function handler () {\n var len = arguments.length, results = new Array(len);\n for(var i = 0; i < len; i++) { results[i] = arguments[i]; }\n\n if (isFunction(selector)) {\n results = tryCatch(selector).apply(ctx, results);\n if (results === errorObj) { return o.onError(results.e); }\n o.onNext(results);\n } else {\n if (results.length <= 1) {\n o.onNext(results[0]);\n } else {\n o.onNext(results);\n }\n }\n\n o.onCompleted();\n };\n}\n\n/**\n * Converts a callback function to an observable sequence.\n *\n * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence.\n * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.\n * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.\n * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.\n */\nObservable.fromCallback = function (fn, ctx, selector) {\n return function () {\n typeof ctx === 'undefined' && (ctx = this); \n\n var len = arguments.length, args = new Array(len)\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return createCbObservable(fn, ctx, selector, args);\n };\n};\n\nfunction createNodeObservable(fn, ctx, selector, args) {\n var o = new AsyncSubject();\n\n args.push(createNodeHandler(o, ctx, selector));\n fn.apply(ctx, args);\n\n return o.asObservable();\n}\n\nfunction createNodeHandler(o, ctx, selector) {\n return function handler () {\n var err = arguments[0];\n if (err) { return o.onError(err); }\n\n var len = arguments.length, results = [];\n for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }\n\n if (isFunction(selector)) {\n var results = tryCatch(selector).apply(ctx, results);\n if (results === errorObj) { return o.onError(results.e); }\n o.onNext(results);\n } else {\n if (results.length <= 1) {\n o.onNext(results[0]);\n } else {\n o.onNext(results);\n }\n }\n\n o.onCompleted();\n };\n}\n\n/**\n * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.\n * @param {Function} fn The function to call\n * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.\n * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.\n * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.\n */\nObservable.fromNodeCallback = function (fn, ctx, selector) {\n return function () {\n typeof ctx === 'undefined' && (ctx = this); \n var len = arguments.length, args = new Array(len);\n for(var i = 0; i < len; i++) { args[i] = arguments[i]; }\n return createNodeObservable(fn, ctx, selector, args);\n };\n};\n\n function isNodeList(el) {\n if (root.StaticNodeList) {\n // IE8 Specific\n // instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8\n return el instanceof root.StaticNodeList || el instanceof root.NodeList;\n } else {\n return Object.prototype.toString.call(el) === '[object NodeList]';\n }\n }\n\n function ListenDisposable(e, n, fn) {\n this._e = e;\n this._n = n;\n this._fn = fn;\n this._e.addEventListener(this._n, this._fn, false);\n this.isDisposed = false;\n }\n ListenDisposable.prototype.dispose = function () {\n if (!this.isDisposed) {\n this._e.removeEventListener(this._n, this._fn, false);\n this.isDisposed = true;\n }\n };\n\n function createEventListener (el, eventName, handler) {\n var disposables = new CompositeDisposable();\n\n // Asume NodeList or HTMLCollection\n var elemToString = Object.prototype.toString.call(el);\n if (isNodeList(el) || elemToString === '[object HTMLCollection]') {\n for (var i = 0, len = el.length; i < len; i++) {\n disposables.add(createEventListener(el.item(i), eventName, handler));\n }\n } else if (el) {\n disposables.add(new ListenDisposable(el, eventName, handler));\n }\n\n return disposables;\n }\n\n /**\n * Configuration option to determine whether to use native events only\n */\n Rx.config.useNativeEvents = false;\n\n var EventObservable = (function(__super__) {\n inherits(EventObservable, __super__);\n function EventObservable(el, name, fn) {\n this._el = el;\n this._n = name;\n this._fn = fn;\n __super__.call(this);\n }\n\n function createHandler(o, fn) {\n return function handler () {\n var results = arguments[0];\n if (isFunction(fn)) {\n results = tryCatch(fn).apply(null, arguments);\n if (results === errorObj) { return o.onError(results.e); }\n }\n o.onNext(results);\n };\n }\n\n EventObservable.prototype.subscribeCore = function (o) {\n return createEventListener(\n this._el,\n this._n,\n createHandler(o, this._fn));\n };\n\n return EventObservable;\n }(ObservableBase));\n\n /**\n * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.\n * @param {Object} element The DOMElement or NodeList to attach a listener.\n * @param {String} eventName The event name to attach the observable sequence.\n * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.\n * @returns {Observable} An observable sequence of events from the specified element and the specified event.\n */\n Observable.fromEvent = function (element, eventName, selector) {\n // Node.js specific\n if (element.addListener) {\n return fromEventPattern(\n function (h) { element.addListener(eventName, h); },\n function (h) { element.removeListener(eventName, h); },\n selector);\n }\n\n // Use only if non-native events are allowed\n if (!Rx.config.useNativeEvents) {\n // Handles jq, Angular.js, Zepto, Marionette, Ember.js\n if (typeof element.on === 'function' && typeof element.off === 'function') {\n return fromEventPattern(\n function (h) { element.on(eventName, h); },\n function (h) { element.off(eventName, h); },\n selector);\n }\n }\n\n return new EventObservable(element, eventName, selector).publish().refCount();\n };\n\n var EventPatternObservable = (function(__super__) {\n inherits(EventPatternObservable, __super__);\n function EventPatternObservable(add, del, fn) {\n this._add = add;\n this._del = del;\n this._fn = fn;\n __super__.call(this);\n }\n\n function createHandler(o, fn) {\n return function handler () {\n var results = arguments[0];\n if (isFunction(fn)) {\n results = tryCatch(fn).apply(null, arguments);\n if (results === errorObj) { return o.onError(results.e); }\n }\n o.onNext(results);\n };\n }\n\n EventPatternObservable.prototype.subscribeCore = function (o) {\n var fn = createHandler(o, this._fn);\n var returnValue = this._add(fn);\n return new EventPatternDisposable(this._del, fn, returnValue);\n };\n\n function EventPatternDisposable(del, fn, ret) {\n this._del = del;\n this._fn = fn;\n this._ret = ret;\n this.isDisposed = false;\n }\n\n EventPatternDisposable.prototype.dispose = function () {\n if(!this.isDisposed) {\n isFunction(this._del) && this._del(this._fn, this._ret);\n }\n };\n\n return EventPatternObservable;\n }(ObservableBase));\n\n /**\n * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.\n * @param {Function} addHandler The function to add a handler to the emitter.\n * @param {Function} [removeHandler] The optional function to remove a handler from an emitter.\n * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.\n * @returns {Observable} An observable sequence which wraps an event from an event emitter\n */\n var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {\n return new EventPatternObservable(addHandler, removeHandler, selector).publish().refCount();\n };\n\n /**\n * Invokes the asynchronous function, surfacing the result through an observable sequence.\n * @param {Function} functionAsync Asynchronous function which returns a Promise to run.\n * @returns {Observable} An observable sequence exposing the function's result value, or an exception.\n */\n Observable.startAsync = function (functionAsync) {\n var promise = tryCatch(functionAsync)();\n if (promise === errorObj) { return observableThrow(promise.e); }\n return observableFromPromise(promise);\n };\n\n var PausableObservable = (function (__super__) {\n inherits(PausableObservable, __super__);\n function PausableObservable(source, pauser) {\n this.source = source;\n this.controller = new Subject();\n\n if (pauser && pauser.subscribe) {\n this.pauser = this.controller.merge(pauser);\n } else {\n this.pauser = this.controller;\n }\n\n __super__.call(this);\n }\n\n PausableObservable.prototype._subscribe = function (o) {\n var conn = this.source.publish(),\n subscription = conn.subscribe(o),\n connection = disposableEmpty;\n\n var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {\n if (b) {\n connection = conn.connect();\n } else {\n connection.dispose();\n connection = disposableEmpty;\n }\n });\n\n return new NAryDisposable([subscription, connection, pausable]);\n };\n\n PausableObservable.prototype.pause = function () {\n this.controller.onNext(false);\n };\n\n PausableObservable.prototype.resume = function () {\n this.controller.onNext(true);\n };\n\n return PausableObservable;\n\n }(Observable));\n\n /**\n * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.\n * @example\n * var pauser = new Rx.Subject();\n * var source = Rx.Observable.interval(100).pausable(pauser);\n * @param {Observable} pauser The observable sequence used to pause the underlying sequence.\n * @returns {Observable} The observable sequence which is paused based upon the pauser.\n */\n observableProto.pausable = function (pauser) {\n return new PausableObservable(this, pauser);\n };\n\n function combineLatestSource(source, subject, resultSelector) {\n return new AnonymousObservable(function (o) {\n var hasValue = [false, false],\n hasValueAll = false,\n isDone = false,\n values = new Array(2),\n err;\n\n function next(x, i) {\n values[i] = x;\n hasValue[i] = true;\n if (hasValueAll || (hasValueAll = hasValue.every(identity))) {\n if (err) { return o.onError(err); }\n var res = tryCatch(resultSelector).apply(null, values);\n if (res === errorObj) { return o.onError(res.e); }\n o.onNext(res);\n }\n isDone && values[1] && o.onCompleted();\n }\n\n return new BinaryDisposable(\n source.subscribe(\n function (x) {\n next(x, 0);\n },\n function (e) {\n if (values[1]) {\n o.onError(e);\n } else {\n err = e;\n }\n },\n function () {\n isDone = true;\n values[1] && o.onCompleted();\n }),\n subject.subscribe(\n function (x) {\n next(x, 1);\n },\n function (e) { o.onError(e); },\n function () {\n isDone = true;\n next(true, 1);\n })\n );\n }, source);\n }\n\n var PausableBufferedObservable = (function (__super__) {\n inherits(PausableBufferedObservable, __super__);\n function PausableBufferedObservable(source, pauser) {\n this.source = source;\n this.controller = new Subject();\n\n if (pauser && pauser.subscribe) {\n this.pauser = this.controller.merge(pauser);\n } else {\n this.pauser = this.controller;\n }\n\n __super__.call(this);\n }\n\n PausableBufferedObservable.prototype._subscribe = function (o) {\n var q = [], previousShouldFire;\n\n function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }\n\n var subscription =\n combineLatestSource(\n this.source,\n this.pauser.startWith(false).distinctUntilChanged(),\n function (data, shouldFire) {\n return { data: data, shouldFire: shouldFire };\n })\n .subscribe(\n function (results) {\n if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) {\n previousShouldFire = results.shouldFire;\n // change in shouldFire\n if (results.shouldFire) { drainQueue(); }\n } else {\n previousShouldFire = results.shouldFire;\n // new data\n if (results.shouldFire) {\n o.onNext(results.data);\n } else {\n q.push(results.data);\n }\n }\n },\n function (err) {\n drainQueue();\n o.onError(err);\n },\n function () {\n drainQueue();\n o.onCompleted();\n }\n );\n return subscription; \n };\n\n PausableBufferedObservable.prototype.pause = function () {\n this.controller.onNext(false);\n };\n\n PausableBufferedObservable.prototype.resume = function () {\n this.controller.onNext(true);\n };\n\n return PausableBufferedObservable;\n\n }(Observable));\n\n /**\n * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,\n * and yields the values that were buffered while paused.\n * @example\n * var pauser = new Rx.Subject();\n * var source = Rx.Observable.interval(100).pausableBuffered(pauser);\n * @param {Observable} pauser The observable sequence used to pause the underlying sequence.\n * @returns {Observable} The observable sequence which is paused based upon the pauser.\n */\n observableProto.pausableBuffered = function (pauser) {\n return new PausableBufferedObservable(this, pauser);\n };\n\n var ControlledObservable = (function (__super__) {\n inherits(ControlledObservable, __super__);\n function ControlledObservable (source, enableQueue, scheduler) {\n __super__.call(this);\n this.subject = new ControlledSubject(enableQueue, scheduler);\n this.source = source.multicast(this.subject).refCount();\n }\n\n ControlledObservable.prototype._subscribe = function (o) {\n return this.source.subscribe(o);\n };\n\n ControlledObservable.prototype.request = function (numberOfItems) {\n return this.subject.request(numberOfItems == null ? -1 : numberOfItems);\n };\n\n return ControlledObservable;\n\n }(Observable));\n\n var ControlledSubject = (function (__super__) {\n inherits(ControlledSubject, __super__);\n function ControlledSubject(enableQueue, scheduler) {\n enableQueue == null && (enableQueue = true);\n\n __super__.call(this);\n this.subject = new Subject();\n this.enableQueue = enableQueue;\n this.queue = enableQueue ? [] : null;\n this.requestedCount = 0;\n this.requestedDisposable = null;\n this.error = null;\n this.hasFailed = false;\n this.hasCompleted = false;\n this.scheduler = scheduler || currentThreadScheduler;\n }\n\n addProperties(ControlledSubject.prototype, Observer, {\n _subscribe: function (o) {\n return this.subject.subscribe(o);\n },\n onCompleted: function () {\n this.hasCompleted = true;\n if (!this.enableQueue || this.queue.length === 0) {\n this.subject.onCompleted();\n this.disposeCurrentRequest();\n } else {\n this.queue.push(Notification.createOnCompleted());\n }\n },\n onError: function (error) {\n this.hasFailed = true;\n this.error = error;\n if (!this.enableQueue || this.queue.length === 0) {\n this.subject.onError(error);\n this.disposeCurrentRequest();\n } else {\n this.queue.push(Notification.createOnError(error));\n }\n },\n onNext: function (value) {\n if (this.requestedCount <= 0) {\n this.enableQueue && this.queue.push(Notification.createOnNext(value));\n } else {\n (this.requestedCount-- === 0) && this.disposeCurrentRequest();\n this.subject.onNext(value);\n }\n },\n _processRequest: function (numberOfItems) {\n if (this.enableQueue) {\n while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {\n var first = this.queue.shift();\n first.accept(this.subject);\n if (first.kind === 'N') {\n numberOfItems--;\n } else {\n this.disposeCurrentRequest();\n this.queue = [];\n }\n }\n }\n\n return numberOfItems;\n },\n request: function (number) {\n this.disposeCurrentRequest();\n var self = this;\n\n this.requestedDisposable = this.scheduler.schedule(number,\n function(s, i) {\n var remaining = self._processRequest(i);\n var stopped = self.hasCompleted || self.hasFailed;\n if (!stopped && remaining > 0) {\n self.requestedCount = remaining;\n\n return disposableCreate(function () {\n self.requestedCount = 0;\n });\n // Scheduled item is still in progress. Return a new\n // disposable to allow the request to be interrupted\n // via dispose.\n }\n });\n\n return this.requestedDisposable;\n },\n disposeCurrentRequest: function () {\n if (this.requestedDisposable) {\n this.requestedDisposable.dispose();\n this.requestedDisposable = null;\n }\n }\n });\n\n return ControlledSubject;\n }(Observable));\n\n /**\n * Attaches a controller to the observable sequence with the ability to queue.\n * @example\n * var source = Rx.Observable.interval(100).controlled();\n * source.request(3); // Reads 3 values\n * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request\n * @param {Scheduler} scheduler determines how the requests will be scheduled\n * @returns {Observable} The observable sequence which only propagates values on request.\n */\n observableProto.controlled = function (enableQueue, scheduler) {\n\n if (enableQueue && isScheduler(enableQueue)) {\n scheduler = enableQueue;\n enableQueue = true;\n }\n\n if (enableQueue == null) { enableQueue = true; }\n return new ControlledObservable(this, enableQueue, scheduler);\n };\n\n var StopAndWaitObservable = (function (__super__) {\n inherits(StopAndWaitObservable, __super__);\n function StopAndWaitObservable (source) {\n __super__.call(this);\n this.source = source;\n }\n\n function scheduleMethod(s, self) {\n self.source.request(1);\n }\n\n StopAndWaitObservable.prototype._subscribe = function (o) {\n this.subscription = this.source.subscribe(new StopAndWaitObserver(o, this, this.subscription));\n return new BinaryDisposable(\n this.subscription,\n defaultScheduler.schedule(this, scheduleMethod)\n );\n };\n\n var StopAndWaitObserver = (function (__sub__) {\n inherits(StopAndWaitObserver, __sub__);\n function StopAndWaitObserver (observer, observable, cancel) {\n __sub__.call(this);\n this.observer = observer;\n this.observable = observable;\n this.cancel = cancel;\n this.scheduleDisposable = null;\n }\n\n StopAndWaitObserver.prototype.completed = function () {\n this.observer.onCompleted();\n this.dispose();\n };\n\n StopAndWaitObserver.prototype.error = function (error) {\n this.observer.onError(error);\n this.dispose();\n };\n\n function innerScheduleMethod(s, self) {\n self.observable.source.request(1);\n }\n\n StopAndWaitObserver.prototype.next = function (value) {\n this.observer.onNext(value);\n this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod);\n };\n\n StopAndWaitObservable.dispose = function () {\n this.observer = null;\n if (this.cancel) {\n this.cancel.dispose();\n this.cancel = null;\n }\n if (this.scheduleDisposable) {\n this.scheduleDisposable.dispose();\n this.scheduleDisposable = null;\n }\n __sub__.prototype.dispose.call(this);\n };\n\n return StopAndWaitObserver;\n }(AbstractObserver));\n\n return StopAndWaitObservable;\n }(Observable));\n\n\n /**\n * Attaches a stop and wait observable to the current observable.\n * @returns {Observable} A stop and wait observable.\n */\n ControlledObservable.prototype.stopAndWait = function () {\n return new StopAndWaitObservable(this);\n };\n\n var WindowedObservable = (function (__super__) {\n inherits(WindowedObservable, __super__);\n function WindowedObservable(source, windowSize) {\n __super__.call(this);\n this.source = source;\n this.windowSize = windowSize;\n }\n\n function scheduleMethod(s, self) {\n self.source.request(self.windowSize);\n }\n\n WindowedObservable.prototype._subscribe = function (o) {\n this.subscription = this.source.subscribe(new WindowedObserver(o, this, this.subscription));\n return new BinaryDisposable(\n this.subscription,\n defaultScheduler.schedule(this, scheduleMethod)\n );\n };\n\n var WindowedObserver = (function (__sub__) {\n inherits(WindowedObserver, __sub__);\n function WindowedObserver(observer, observable, cancel) {\n this.observer = observer;\n this.observable = observable;\n this.cancel = cancel;\n this.received = 0;\n this.scheduleDisposable = null;\n __sub__.call(this);\n }\n\n WindowedObserver.prototype.completed = function () {\n this.observer.onCompleted();\n this.dispose();\n };\n\n WindowedObserver.prototype.error = function (error) {\n this.observer.onError(error);\n this.dispose();\n };\n\n function innerScheduleMethod(s, self) {\n self.observable.source.request(self.observable.windowSize);\n }\n\n WindowedObserver.prototype.next = function (value) {\n this.observer.onNext(value);\n this.received = ++this.received % this.observable.windowSize;\n this.received === 0 && (this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod));\n };\n\n WindowedObserver.prototype.dispose = function () {\n this.observer = null;\n if (this.cancel) {\n this.cancel.dispose();\n this.cancel = null;\n }\n if (this.scheduleDisposable) {\n this.scheduleDisposable.dispose();\n this.scheduleDisposable = null;\n }\n __sub__.prototype.dispose.call(this);\n };\n\n return WindowedObserver;\n }(AbstractObserver));\n\n return WindowedObservable;\n }(Observable));\n\n /**\n * Creates a sliding windowed observable based upon the window size.\n * @param {Number} windowSize The number of items in the window\n * @returns {Observable} A windowed observable based upon the window size.\n */\n ControlledObservable.prototype.windowed = function (windowSize) {\n return new WindowedObservable(this, windowSize);\n };\n\n /**\n * Pipes the existing Observable sequence into a Node.js Stream.\n * @param {Stream} dest The destination Node.js stream.\n * @returns {Stream} The destination stream.\n */\n observableProto.pipe = function (dest) {\n var source = this.pausableBuffered();\n\n function onDrain() {\n source.resume();\n }\n\n dest.addListener('drain', onDrain);\n\n source.subscribe(\n function (x) {\n !dest.write(String(x)) && source.pause();\n },\n function (err) {\n dest.emit('error', err);\n },\n function () {\n // Hack check because STDIO is not closable\n !dest._isStdio && dest.end();\n dest.removeListener('drain', onDrain);\n });\n\n source.resume();\n\n return dest;\n };\n\n var MulticastObservable = (function (__super__) {\n inherits(MulticastObservable, __super__);\n function MulticastObservable(source, fn1, fn2) {\n this.source = source;\n this._fn1 = fn1;\n this._fn2 = fn2;\n __super__.call(this);\n }\n\n MulticastObservable.prototype.subscribeCore = function (o) {\n var connectable = this.source.multicast(this._fn1());\n return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());\n };\n\n return MulticastObservable;\n }(ObservableBase));\n\n /**\n * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each\n * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's\n * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.\n *\n * @example\n * 1 - res = source.multicast(observable);\n * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });\n *\n * @param {Function|Subject} subjectOrSubjectSelector\n * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.\n * Or:\n * Subject to push source elements into.\n *\n * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if