@lifaon/rx-js-light
Version:
Blazing fast Observables
49 lines (48 loc) • 1.32 kB
JavaScript
import {freeze} from "../../../../../misc/helpers/freeze.mjs";
import {noop} from "../../../../../misc/helpers/noop.mjs";
export function createMulticastSource() {
let _emitFunctions = [];
let _dispatchingObservers;
let _dispatchingCount = 0;
const cloneObservers = () => {
if (_emitFunctions === _dispatchingObservers) {
_emitFunctions = _emitFunctions.slice();
}
};
const emit = value => {
if (_dispatchingCount === 0) {
_dispatchingObservers = _emitFunctions;
_dispatchingCount = _dispatchingObservers.length;
for (let i = 0; _dispatchingCount > 0; i++) {
_dispatchingCount--;
_dispatchingObservers[i](value);
}
} else {
throw new Error(`Already dispatching.`);
}
};
const subscribe = emit => {
let running = true;
if (_dispatchingCount > 0) {
cloneObservers();
}
_emitFunctions.push(emit);
return () => {
if (running) {
running = false;
if (_dispatchingCount > 0) {
cloneObservers();
_dispatchingObservers[_dispatchingObservers.indexOf(emit)] = noop;
}
_emitFunctions.splice(_emitFunctions.indexOf(emit), 1);
}
};
};
return freeze({
getObservers: () => {
return _emitFunctions;
},
emit,
subscribe
});
}