Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active May 15, 2023 14:27
Show Gist options
  • Save cowboyd/3da4b5596b9cc3b5a2cef9d571019ba8 to your computer and use it in GitHub Desktop.
Save cowboyd/3da4b5596b9cc3b5a2cef9d571019ba8 to your computer and use it in GitHub Desktop.
export interface HeartbeatAction {
type: "heartbeat";
count: number;
}
/**
* Consistently produce a heartbeat reliably every 500ms
*/
export function* produce() {
let count = 1;
while (true) {
yield* sleep(500);
yield* put({type: "heartbeat", count });
}
}
/**
* Takes a heart beat, and then simulates some asynchronous "work" that takes anywhere from
* 0 to 1000ms. It is deliberately out of phase with the producer so that there will be times
* when a heartbeat is generated that this is not yielded in `take()`
*/
function* consume() {
while (true) {
let beat: HeartbeatAction = yield* take({type: "heartbeat"});
yield* sleep(Math.random() * 100);
console.log(`beat ${beat.count}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment