Last active
May 15, 2023 14:27
-
-
Save cowboyd/3da4b5596b9cc3b5a2cef9d571019ba8 to your computer and use it in GitHub Desktop.
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
export interface HeartbeatAction { | |
type: "heartbeat"; | |
count: number; | |
} |
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
/** | |
* Consistently produce a heartbeat reliably every 500ms | |
*/ | |
export function* produce() { | |
let count = 1; | |
while (true) { | |
yield* sleep(500); | |
yield* put({type: "heartbeat", count }); | |
} | |
} |
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
/** | |
* 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