1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/packages/utility-features/utilities/src/wait.ts
Sebastian Malton 13673eaac4 Move all utility functions to separate package
Signed-off-by: Sebastian Malton <sebastian@malton.name>
2023-03-02 13:30:24 -05:00

55 lines
1.2 KiB
TypeScript

/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { IComputedValue } from "mobx";
import { runInAction, when } from "mobx";
import type { Disposer } from "@k8slens/utilities";
export async function waitUntilDefined<T>(getter: (() => T | null | undefined) | IComputedValue<T | null | undefined>, opts?: { timeout?: number }): Promise<T> {
return new Promise<T>((resolve, reject) => {
when(
() => {
const res = typeof getter === "function"
? getter()
: getter.get();
const isDefined = res != null;
if (isDefined) {
resolve(res);
}
return isDefined;
},
() => {},
{
onError: reject,
...(opts ?? {}),
},
);
});
}
export function onceDefined<T>(getter: () => T | null | undefined, action: (val: T) => void): Disposer {
let res: T | null | undefined;
return when(
() => {
res = getter();
if (res != null) {
const r = res;
runInAction(() => {
action(r);
});
return true;
}
return false;
},
() => {},
);
}