(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@most/prelude')) : typeof define === 'function' && define.amd ? define(['exports', '@most/prelude'], factory) : (factory((global.mostMulticast = global.mostMulticast || {}),global.mostPrelude)); }(this, (function (exports,_most_prelude) { 'use strict'; var MulticastDisposable = function MulticastDisposable (source, sink) { this.source = source this.sink = sink this.disposed = false }; MulticastDisposable.prototype.dispose = function dispose () { if (this.disposed) { return } this.disposed = true var remaining = this.source.remove(this.sink) return remaining === 0 && this.source._dispose() }; function tryEvent (t, x, sink) { try { sink.event(t, x) } catch (e) { sink.error(t, e) } } function tryEnd (t, x, sink) { try { sink.end(t, x) } catch (e) { sink.error(t, e) } } var dispose = function (disposable) { return disposable.dispose(); } var emptyDisposable = { dispose: function dispose$1 () {} } var MulticastSource = function MulticastSource (source) { this.source = source this.sinks = [] this._disposable = emptyDisposable }; MulticastSource.prototype.run = function run (sink, scheduler) { var n = this.add(sink) if (n === 1) { this._disposable = this.source.run(this, scheduler) } return new MulticastDisposable(this, sink) }; MulticastSource.prototype._dispose = function _dispose () { var disposable = this._disposable this._disposable = emptyDisposable return Promise.resolve(disposable).then(dispose) }; MulticastSource.prototype.add = function add (sink) { this.sinks = _most_prelude.append(sink, this.sinks) return this.sinks.length }; MulticastSource.prototype.remove = function remove$1 (sink) { var i = _most_prelude.findIndex(sink, this.sinks) // istanbul ignore next if (i >= 0) { this.sinks = _most_prelude.remove(i, this.sinks) } return this.sinks.length }; MulticastSource.prototype.event = function event (time, value) { var s = this.sinks if (s.length === 1) { return s[0].event(time, value) } for (var i = 0; i < s.length; ++i) { tryEvent(time, value, s[i]) } }; MulticastSource.prototype.end = function end (time, value) { var s = this.sinks for (var i = 0; i < s.length; ++i) { tryEnd(time, value, s[i]) } }; MulticastSource.prototype.error = function error (time, err) { var s = this.sinks for (var i = 0; i < s.length; ++i) { s[i].error(time, err) } }; function multicast (stream) { var source = stream.source return source instanceof MulticastSource ? stream : new stream.constructor(new MulticastSource(source)) } exports['default'] = multicast; exports.MulticastSource = MulticastSource; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=multicast.js.map