gpt4 book ai didi

stream - 如何以阻塞方式有效地提取 futures::Stream 的第一个元素?

转载 作者:行者123 更新时间:2023-11-29 08:34:46 26 4
gpt4 key购买 nike

我有以下方法:

pub fn load_names(&self, req: &super::MagicQueryType) -> ::grpcio::Result<::grpcio::ClientSStreamReceiver<String>> {

我的目标是获得 grpcio::ClientSStreamReceiver 的第一个元素;我不关心其他名字:

let name: String = load_names(query)?.wait().nth(0)?;

nth(0) 之前调用 wait() 似乎效率低下,因为我相信 wait() 会阻塞流,直到它收到所有元素。

如何在不触发构建错误的情况下编写更高效的解决方案(即 nth(0).wait())? Rust 的 futures::stream::Stream 构建错误让我感到非常困惑。

Rust playground不支持 grpcio = "0.4.4" 所以我无法提供链接。

最佳答案

要以阻塞方式提取futures::Stream 的第一个元素,您应该通过调用executor::block_on_streamStream 转换为迭代器。然后调用Iterator::next .

use futures::{executor, stream, Stream}; // 0.3.4
use std::iter;

fn example() -> impl Stream<Item = i32> {
stream::iter(iter::repeat(42))
}

fn main() {
let v = executor::block_on_stream(example()).next();
println!("{:?}", v);
}

如果您使用的是 Tokio,您可以使用 StreamExt::into_futureStream 转换为 Future并用 #[tokio::main] 注释函数:

use futures::{stream, Stream, StreamExt}; // 0.3.4
use std::iter;
use tokio; // 0.2.13

fn example() -> impl Stream<Item = i32> {
stream::iter(iter::repeat(42))
}

#[tokio::main]
async fn just_one() -> Option<i32> {
let (i, _stream) = example().into_future().await;
i
}

fn main() {
println!("{:?}", just_one());
}

另见:

关于stream - 如何以阻塞方式有效地提取 futures::Stream 的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com