Files
DEVICE_CONTACT/src/renderer/lazy-resource.ts
2025-12-17 23:19:04 +02:00

46 lines
842 B
TypeScript

export type LazyResource<T> = {
load: () => Promise<T>;
unload: () => void;
isLoaded: () => boolean;
};
export function createLazyResource<T>(
loader: () => Promise<T>,
dispose?: (value: T) => void
): LazyResource<T> {
let cached: T | null = null;
let inflight: Promise<T> | null = null;
const load = async (): Promise<T> => {
if (cached) return cached;
if (inflight) return inflight;
inflight = (async () => {
const value = await loader();
cached = value;
inflight = null;
return value;
})();
return inflight;
};
const unload = () => {
if (cached && dispose) {
try {
dispose(cached);
} catch (error) {
console.error("[lazy-resource] failed to dispose resource", error);
}
}
cached = null;
inflight = null;
};
return {
load,
unload,
isLoaded: () => cached !== null
};
}