1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

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>
This commit is contained in:
Sebastian Malton 2022-09-14 11:47:28 -04:00
parent cd6df109aa
commit 2cfe5577d0
2 changed files with 44 additions and 1 deletions

View File

@ -0,0 +1,43 @@
/**
* 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;
},
};
},
});
}

View File

@ -17,7 +17,7 @@ export interface InitializableState<T> {
init: () => Promise<void>;
}
type InitializableStateValue<T> =
export type InitializableStateValue<T> =
| { set: false }
| { set: true; value: T } ;