Await on variable number of futures

The select! macro allows to listen on multiple futures.

async fn race_tasks() {
    let t1 = task_one().fuse();
    let t2 = task_two().fuse();

    pin_mut!(t1, t2);

    select! {
        () = t1 => println!("task one completed first"),
        () = t2 => println!("task two completed first"),
    }
}

But it seems select! only allows to await on a fixed number of futures.

I have a variable number of streams, the number changes on the fly.
Is there a way to await on them?
When any of them is signalled, I want my code executed.

Check the documentation for FuturesUnordered: https://docs.rs/futures-preview/0.3.0-alpha.18/futures/stream/struct.FuturesUnordered.html

That might be a better option for your use case.

3 Likes