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:
parent
cd6df109aa
commit
2cfe5577d0
43
src/common/initializable-state/create-lazy.ts
Normal file
43
src/common/initializable-state/create-lazy.ts
Normal 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;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -17,7 +17,7 @@ export interface InitializableState<T> {
|
||||
init: () => Promise<void>;
|
||||
}
|
||||
|
||||
type InitializableStateValue<T> =
|
||||
export type InitializableStateValue<T> =
|
||||
| { set: false }
|
||||
| { set: true; value: T } ;
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user