Last active
January 6, 2024 02:03
-
-
Save cowboyd/5f7a17c9350d0148a606fdff99ae88c0 to your computer and use it in GitHub Desktop.
Implement a restartable operation from any operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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