1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/common/initializable-state/create-lazy.ts
Sebastian Malton 2cfe5577d0 Introduce LazyInitializableState
- Given a syncronous init function we can just lazily do the
  initialization at first call to get() instead of having to declare
  a new unique runnable

Signed-off-by: Sebastian Malton <sebastian@malton.name>
2022-10-31 14:42:03 -04:00

44 lines
1.1 KiB
TypeScript

/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection, Injectable } from "@ogre-tools/injectable";
import { getInjectable } from "@ogre-tools/injectable";
import type { InitializableStateValue } from "./create";
export interface CreateLazyInitializableStateArgs<T> {
id: string;
init: (di: DiContainerForInjection) => T;
}
export interface LazyInitializableState<T> {
get: () => T;
}
export function createLazyInitializableState<T>(args: CreateLazyInitializableStateArgs<T>): Injectable<LazyInitializableState<T>, unknown, void> {
const { id, init } = args;
return getInjectable({
id,
instantiate: (di): LazyInitializableState<T> => {
let box: InitializableStateValue<T> = {
set: false,
};
return {
get: () => {
if (box.set === false) {
box = {
set: true,
value: init(di),
};
}
return box.value;
},
};
},
});
}