I find it is not easy to use StreamExt methods which accept a closure returns Future(by async block).
use futures;
use async_std::task;
// failed: borrowed data cannot be stored outside of its closure
fn test_scan_futures() {
use futures::stream::{Stream, StreamExt};
let s = futures::stream::iter(vec![1i32, 2, 3, 4, 5]);
let res = s.scan(3, |th, i| {
async {
Some(if i > *th { i } else { 0 })
}
}).collect::<Vec<i32>>();
task::block_on(res);
}
// works!
fn test_scan_astd() {
use async_std::stream::{Stream, StreamExt};
let s = futures::stream::iter(vec![1i32, 2, 3, 4, 5]);
let res = s.scan(3, |th, i| {
Some(if i > *th { i } else { 0 })
}).collect::<Vec<i32>>();
task::block_on(res);
}
fn scan<S, B, Fut, F>(self, initial_state: S, f: F) -> Scan<Self, S, Fut, F>where F: FnMut(&mut S, Self::Item) -> Fut, Fut: Future<Output = Option<B>>,
- What is the lifetime of
Fut
? - How can I borrow
&mut S
inside an async block? - Is there someway to share data with async block?