Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active January 6, 2024 02:03
Show Gist options
  • Save cowboyd/5f7a17c9350d0148a606fdff99ae88c0 to your computer and use it in GitHub Desktop.
Save cowboyd/5f7a17c9350d0148a606fdff99ae88c0 to your computer and use it in GitHub Desktop.
Implement a restartable operation from any operation
import {
createChannel,
each,
Operation,
resource,
spawn,
Task,
} from "effection";
export function useRestartable<TArgs extends unknown[]>(
op: (...args: TArgs) => Operation<void>,
) {
return resource<(...args: TArgs) => Operation<void>>(function* (provide) {
let invocations = createChannel<TArgs, never>();
let current: Task<void> | undefined = undefined;
yield* spawn(function* () {
for (let args of yield* each(invocations)) {
if (current) {
yield* current.halt();
}
current = yield* spawn(() => op(...args));
yield* each.next();
}
});
yield* provide(function* restart(...args) {
yield* invocations.send(args);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment