How to use take_while with futures::Stream?

爱⌒轻易说出口 提交于 2019-12-02 11:58:40

take_while expects the closure to return a future, or something that can be converted to a future. bool doesn't implement IntoFuture, so you have to wrap it in a future instead. future::ok returns a future that is immediately ready with the specified value.

use futures::{future, stream, Stream}; // 0.1.25

fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
    stream::iter_ok(0..i)
}

fn main() {
    println!("start:");
    let foo = into_many(10)
        .take_while(|&x| { future::ok(x < 10) })
        .map(|x| {
            println!("number={}", x);
            x
        })
        .wait();

    for _ in foo {}

    println!("finish:");
}

wait returns an iterator version of the stream, but that iterator remains lazy, which means you need to iterate it to actually execute your closure:

use futures::{stream, Stream}; // 0.1.25

fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
    stream::iter_ok(0..i)
}

fn main() {
    println!("start:");
    let foo = into_many(10)
        // .take_while(|x| { x < 10 })
        .map(|x| {
            println!("number={}", x);
            x
        })
        .wait();

    for _ in foo {} // ← this

    println!("finish:");
}

(link to playground)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!