How to use take_while with futures::Stream?

后端 未结 2 924
慢半拍i
慢半拍i 2021-01-26 16:32

I\'m trying to understand what syntax should I use for take_while() with futures::Stream; crate (0.1.25). Here\'s a piece of code (on playground):

u         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 17:21

    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 {
        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)

提交回复
热议问题