1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/packages/utility-features/startable-stoppable/src/get-startable-stoppable.ts
Janne Savolainen 58aef0ff73
Extract startable-stoppable to NPM package
Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
2023-03-17 08:50:24 +02:00

41 lines
924 B
TypeScript

export type Stopper = () => void;
export type Starter = () => Stopper;
export interface StartableStoppable {
readonly started: boolean;
start: () => void;
stop: () => void;
}
type StartableStoppableState = "stopped" | "started" | "starting";
export function getStartableStoppable(id: string, startAndGetStopper: Starter): StartableStoppable {
let stop: Stopper;
let state: StartableStoppableState = "stopped";
return {
get started() {
return state === "started";
},
start: () => {
if (state !== "stopped") {
throw new Error(`Tried to start "${id}", but it is already ${state}.`);
}
state = "starting";
stop = startAndGetStopper();
state = "started";
},
stop: () => {
if (state !== "started") {
throw new Error(`Tried to stop "${id}", but it is already ${state}.`);
}
stop();
state = "stopped";
},
};
}