迭代与并发

与同步的Iterator类似,有很多不同的方法可以迭代处理Stream中的值。有很多组合子风格 的方法,如mapfilterfold,以及它们的“遇错即断”版本try_maptry_filtertry_fold

不幸的是,for循环不能用在Stream上,但是对于命令式编程风格(imperative style)的 代码,while let以及next/try_next函数还可以使用:


# #![allow(unused_variables)]
#fn main() {
async fn sum_with_next(mut stream: Pin<&mut dyn Stream<Item = i32>>) -> i32 {
    use futures::stream::StreamExt; // for `next`
    let mut sum = 0;
    while let Some(item) = stream.next().await {
        sum += item;
    }
    sum
}

async fn sum_with_try_next(
    mut stream: Pin<&mut dyn Stream<Item = Result<i32, io::Error>>>,
) -> Result<i32, io::Error> {
    use futures::stream::TryStreamExt; // for `try_next`
    let mut sum = 0;
    while let Some(item) = stream.try_next().await? {
        sum += item;
    }
    Ok(sum)
}
#}

然而,如果我们每次只处理一个元素,我们就要是去并发的机会,毕竟这是我们编写异步代码的首要 目的。为了并发处理一个Stream的多个值,使用for_each_concurrenttry_for_each_concurrent方法:


# #![allow(unused_variables)]
#fn main() {
async fn jump_around(
    mut stream: Pin<&mut dyn Stream<Item = Result<u8, io::Error>>>,
) -> Result<(), io::Error> {
    use futures::stream::TryStreamExt; // for `try_for_each_concurrent`
    const MAX_CONCURRENT_JUMPERS: usize = 100;

    stream.try_for_each_concurrent(MAX_CONCURRENT_JUMPERS, |num| async move {
        jump_n_times(num).await?;
        report_n_jumps(num).await?;
        Ok(())
    }).await?;

    Ok(())
}
#}