Asynchronous 有没有办法创建一个异步流生成器,生成重复调用函数的结果?
我想建立一个程序,收集天气更新,并将其表示为一个流。我想在无限循环中调用Asynchronous 有没有办法创建一个异步流生成器,生成重复调用函数的结果?,asynchronous,rust,async-await,rust-tokio,Asynchronous,Rust,Async Await,Rust Tokio,我想建立一个程序,收集天气更新,并将其表示为一个流。我想在无限循环中调用get_weather(),在finish和start之间有60秒的延迟 简化版本如下所示: async fn get_weather() -> Weather { /* ... */ } fn get_weather_stream() -> impl futures::Stream<Item = Weather> { loop { tokio::timer::delay_f
get_weather()
,在finish和start之间有60秒的延迟
简化版本如下所示:
async fn get_weather() -> Weather { /* ... */ }
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
loop {
tokio::timer::delay_for(std::time::Duration::from_secs(60)).await;
let weather = get_weather().await;
yield weather; // This is not supported
// Note: waiting for get_weather() stops the timer and avoids overflows.
}
}
如果发生这种情况,下一个函数将立即启动。我想在上一个get_weather()
start和下一个get_weather()
start之间保持60秒。用于从“未来世界”转到“流的世界”。我们不需要任何额外的状态,所以我们使用空元组:
use futures::StreamExt; // 0.3.4
use std::time::Duration;
use tokio::time; // 0.2.11
struct Weather;
async fn get_weather() -> Weather {
Weather
}
const BETWEEN: Duration = Duration::from_secs(1);
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
futures::stream::unfold((), |_| async {
time::delay_for(BETWEEN).await;
let weather = get_weather().await;
Some((weather, ()))
})
}
#[tokio::main]
async fn main() {
get_weather_stream()
.take(3)
.for_each(|_v| async {
println!("Got the weather");
})
.await;
}
另见:
get\u weather()
?我想在每次迭代中将它传递到get\u weather\u stream()
,然后传递到get\u weather()
。当然,生成的流应该是依赖于该变量的生命周期。@peku33我现在不明白为什么它不能工作。也许你应该试试,然后回来报到!在第一步中,我添加了@peku33
use futures::StreamExt; // 0.3.4
use std::time::Duration;
use tokio::time; // 0.2.11
struct Weather;
async fn get_weather() -> Weather {
Weather
}
const BETWEEN: Duration = Duration::from_secs(1);
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
futures::stream::unfold((), |_| async {
time::delay_for(BETWEEN).await;
let weather = get_weather().await;
Some((weather, ()))
})
}
#[tokio::main]
async fn main() {
get_weather_stream()
.take(3)
.for_each(|_v| async {
println!("Got the weather");
})
.await;
}