diff --git a/src/common/initializable-state/create-lazy.ts b/src/common/initializable-state/create-lazy.ts new file mode 100644 index 0000000000..ca6a8f41bc --- /dev/null +++ b/src/common/initializable-state/create-lazy.ts @@ -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 { + id: string; + init: (di: DiContainerForInjection) => T; +} + +export interface LazyInitializableState { + get: () => T; +} + +export function createLazyInitializableState(args: CreateLazyInitializableStateArgs): Injectable, unknown, void> { + const { id, init } = args; + + return getInjectable({ + id, + instantiate: (di): LazyInitializableState => { + let box: InitializableStateValue = { + set: false, + }; + + return { + get: () => { + if (box.set === false) { + box = { + set: true, + value: init(di), + }; + } + + return box.value; + }, + }; + }, + }); +} diff --git a/src/common/initializable-state/create.ts b/src/common/initializable-state/create.ts index 829de57d94..1016680272 100644 --- a/src/common/initializable-state/create.ts +++ b/src/common/initializable-state/create.ts @@ -17,7 +17,7 @@ export interface InitializableState { init: () => Promise; } -type InitializableStateValue = +export type InitializableStateValue = | { set: false } | { set: true; value: T } ;