How to Build a Pub/Sub System in Rust

Build a Rust Pub/Sub system using tokio channels to decouple message producers from multiple consumers.

You build a Pub/Sub system in Rust by using the tokio runtime for async I/O and tokio::sync::broadcast or tokio::sync::mpsc channels to decouple publishers from subscribers.

use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel::<String>(16);
    let mut rx2 = tx.subscribe();

    tokio::spawn(async move {
        tx.send("Hello from publisher").unwrap();
    });

    println!("Subscriber 1: {}", rx1.recv().await.unwrap());
    println!("Subscriber 2: {}", rx2.recv().await.unwrap());
}

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