#Is it possible to use Iterators + collect with async computation?

7 messages · Page 1 of 1 (latest)

untold jewel
#

Hello. I think my question can be pretty well described via this Rust playground link:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=57df2473f7b253fe99d4e6dfb9b42344

I have some computation that I want to do on a collection that involves async, and I want to collect it at the end. Even if I use futures::stream::StreamExt, I still can't seem to get this to work. Any advice? Should I just use a for loop?

untold jewel
fallen briar
#

ah…

#

?play

use std::fmt::Display;
use std::collections::HashMap;
use futures::prelude::*;
async fn compute_label(inp: impl Display) -> String {
    format!("{}", inp)
}
async fn compute_value(inp: impl Display) -> String {
    format!("Hello, {}!", inp)
}

#[tokio::main]
async fn main() {
    let my_collection: HashMap<String, String> = futures::stream::iter(0..10)
        .then(|i| async move {
            let label = compute_label(i).await;
            let value = compute_value(i).await;
            (label, value) 
        })
        .collect()
        .await;
        
    println!("{:?}", my_collection);
}
modest palmBOT
#
     Running `target/debug/playground`

{"5": "Hello, 5!", "1": "Hello, 1!", "7": "Hello, 7!", "9": "Hello, 9!", "8": "Hello, 8!", "0": "Hello, 0!", "6": "Hello, 6!", "2": "Hello, 2!", "3": "Hello, 3!", "4": "Hello, 4!"}
fallen briar
#

when you want to do something async to a stream's items you use .then() instead of .map()