Function zng::task::channel::unbounded

source ·
pub fn unbounded<T>() -> (UnboundSender<T>, Receiver<T>)
Expand description

Create a channel with no maximum capacity.

Unbound channels always send messages immediately, never yielding on await. If the messages are no received they accumulate in the channel buffer.

§Examples

The example spawns two parallel tasks, the receiver task takes a while to start receiving but then rapidly consumes all messages in the buffer and new messages as they are send.

use zng_task::{self as task, channel};

let (sender, receiver) = channel::unbounded();

task::spawn(async move {
    for msg in ["Hello!", "Are you still there?"].into_iter().cycle() {
        task::deadline(300.ms()).await;
        if let Err(e) = sender.send(msg) {
            eprintln!("no receiver connected, the message `{}` was not send", e.0);
            break;
        }
    }
});
task::spawn(async move {
    task::deadline(5.secs()).await;
     
    loop {
        match receiver.recv().await {
            Ok(msg) => println!("{msg}"),
            Err(_) => {
                eprintln!("no message in channel and no sender connected");
                break;
            }
        }
    }
});

Note that you don’t need to .await on send as there is always space in the channel buffer.