Skip to content

Commit

Permalink
Refactored Promise logic types to make it more clear
Browse files Browse the repository at this point in the history
  • Loading branch information
brunocangs committed Jul 16, 2024
1 parent 4c64a19 commit 953e31b
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions examples/01_typescript/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,14 @@ const Toggle = () => {
);
};

type PromiseLogicOutput = string;
type PromiseLogicInput = { duration: number };
type PromiseLogicEvents =
| { type: 'elapsed'; value: number }
| { type: 'completed' };

const promiseLogicAtom = atom(
fromPromise<string, { duration: number }, { type: 'elapsed'; value: number }>(
fromPromise<PromiseLogicOutput, PromiseLogicInput, PromiseLogicEvents>(
async ({ emit, input }) => {
const start = Date.now();
let now = Date.now();
Expand All @@ -117,6 +123,8 @@ const promiseLogicAtom = atom(
emit({ type: 'elapsed', value: now - start });
now = Date.now();
} while (now - start < input.duration);

emit({ type: 'completed' });
return 'Promise finished';
},
),
Expand Down Expand Up @@ -144,8 +152,14 @@ const PromiseActor = () => {
const [input, setInput] = useAtom(durationAtom);

useEffect(() => {
const sub = actor.on('elapsed', (event) => setElapsed(event.value));
return sub.unsubscribe;
const elapsedSub = actor.on('elapsed', (event) => setElapsed(event.value));
const completedSub = actor.on('completed', () =>
window.alert('Promise completed'),
);
return () => {
elapsedSub.unsubscribe();
completedSub.unsubscribe();
};
}, [actor, setElapsed]);

return (
Expand Down

0 comments on commit 953e31b

Please sign in to comment.