How to use tokio broadcast channel

Create a broadcast channel with tokio::sync::broadcast::channel to send messages from one sender to multiple async receivers.

Use tokio::sync::broadcast::channel to create a sender and receiver, then send messages with send and receive them with recv in an async loop.

use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = broadcast::channel::<String>(16);
    
    // Spawn a sender task
    tokio::spawn(async move {
        tx.send("Hello".to_string()).unwrap();
        tx.send("World".to_string()).unwrap();
    });

    // Receive messages
    while let Ok(msg) = rx.recv().await {
        println!("Received: {msg}");
    }
}

Add tokio = { version = "1", features = ["sync"] } to your Cargo.toml.