Add a demo of the timeout method

This commit is contained in:
Manuel Thalmann 2025-04-10 08:20:03 +02:00
parent bd4528edf0
commit 0706bae9f7
Signed by: manuth
SSH key fingerprint: SHA256:HsMLC+7kJWALP6YCYCoopxNbUnghwSGLVcG76SECT5c

View file

@ -1,22 +1,32 @@
use std::{pin::pin, time::Duration};
use trpl::{ReceiverStream, Stream, StreamExt};
fn main() {
trpl::run(async {
let mut messages = get_messages();
let mut messages =
pin!(get_messages().timeout(Duration::from_millis(200)));
while let Some(message) = messages.next().await {
println!("{message}");
while let Some(result) = messages.next().await {
match result {
Ok(message) => println!("{message}"),
Err(reason) => eprintln!("Problem: {reason:?}"),
}
}
});
})
}
fn get_messages() -> impl Stream<Item = String> {
let (tx, rx) = trpl::channel();
let messages = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
for message in messages {
tx.send(format!("Message: '{message}'")).unwrap();
}
trpl::spawn_task(async move {
let messages = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
for (index, message) in messages.into_iter().enumerate() {
let time_to_sleep = if index % 2 == 0 { 100 } else { 300 };
trpl::sleep(Duration::from_millis(time_to_sleep)).await;
tx.send(format!("Message: '{message}'")).unwrap();
}
});
ReceiverStream::new(rx)
}