chore: init clean tree
This commit is contained in:
45
src/renderer/lazy-resource.ts
Normal file
45
src/renderer/lazy-resource.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
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
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user