How to Write a Custom Future in Rust

Create a custom Future in Rust by wrapping asynchronous logic in an `async` block or function and using `.await` to suspend execution.

You write a custom Future in Rust by defining an async block or function, which the compiler transforms into a state machine implementing the Future trait. Use the async keyword to mark the block, then await operations inside it to suspend execution until I/O completes.

use std::time::Duration;

fn main() {
    trpl::block_on(async {
        let (tx, mut rx) = trpl::channel();

        let tx_fut = async move {
            let vals = vec![
                String::from("hi"),
                String::from("from"),
                String::from("the"),
                String::from("future"),
            ];

            for val in vals {
                tx.send(val).unwrap();
                trpl::sleep(Duration::from_millis(500)).await;
            }
        };

        let rx_fut = async {
            while let Some(value) = rx.recv().await {
                println!("received '{value}'");
            }
        };

        trpl::join(tx_fut, rx_fut).await;
    });
}