viem
Version:
49 lines • 1.7 kB
JavaScript
/** @internal */
export const listenersCache = /*#__PURE__*/ new Map();
/** @internal */
export const cleanupCache = /*#__PURE__*/ new Map();
let callbackCount = 0;
/**
* @description Sets up an observer for a given function. If another function
* is set up under the same observer id, the function will only be called once
* for both instances of the observer.
*/
export function observe(observerId, callbacks, fn) {
const callbackId = ++callbackCount;
const getListeners = () => listenersCache.get(observerId) || [];
const unsubscribe = () => {
const listeners = getListeners();
listenersCache.set(observerId, listeners.filter((cb) => cb.id !== callbackId));
};
const unwatch = () => {
const listeners = getListeners();
if (!listeners.some((cb) => cb.id === callbackId))
return;
const cleanup = cleanupCache.get(observerId);
if (listeners.length === 1 && cleanup)
cleanup();
unsubscribe();
};
const listeners = getListeners();
listenersCache.set(observerId, [
...listeners,
{ id: callbackId, fns: callbacks },
]);
if (listeners && listeners.length > 0)
return unwatch;
const emit = {};
for (const key in callbacks) {
emit[key] = ((...args) => {
const listeners = getListeners();
if (listeners.length === 0)
return;
for (const listener of listeners)
listener.fns[key]?.(...args);
});
}
const cleanup = fn(emit);
if (typeof cleanup === 'function')
cleanupCache.set(observerId, cleanup);
return unwatch;
}
//# sourceMappingURL=observe.js.map