-
-
Save peterbudai/0725a75b35c612d32af15b28f67de53d to your computer and use it in GitHub Desktop.
Function to generate an async stream that yields an event every second
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
fn create_countdown_stream(duration: Duration) -> impl Stream<Item = Event, Error = io::Error> { | |
let start = Instant::now(); | |
Interval::new(start, Duration::from_secs(1)) | |
.map(move |now| { | |
Event::Countdown( | |
// Include the remaining seconds in the event, but value should never below zero | |
duration | |
.checked_sub(now.duration_since(start)) | |
.map_or(0, |rem| rem.as_secs()), | |
) | |
}) | |
.map_err(|err| io::Error::new(io::ErrorKind::Other, err)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment