Returning Stream of values or Stream of Futures?

⚓ Rust    📅 2025-12-15    👤 surdeus    👁️ 4      

surdeus

Hello,

I wrote a trait and its implementation for an Iterator that looked like this:

impl<T> FooBar for T
    where T: IntoIterator<Item = Foo>
{
    async fn do_some_async(self) -> impl Stream<Item = Result<Vec<u8>, io::Error>> {
        stream::iter(self).map(|inp| async move {
            do_something(inp).await
        })
        .buffer_unordered(8)
    }
}

And then I realised that I would like to call .buffer_unordered(8) with a different number or maybe use an ordered buffer.

So I realised I could change the trait and the implementation to:

impl<T> FooBar for T
    where T: IntoIterator<Item = Foo>
{
    async fn do_some_async(self) -> impl Stream<Item = impl Future<Output = Result<Vec<u8>, io::Error>>> {
        stream::iter(self).map(|inp| async move {
            do_something(inp).await
        })
    }
}

and run it for example like .do_some_async().await.buffer_unordered(4).collect::<Vec<Result<Vec<u8>, io::Error>>>().await.

And it works!

The question I have is whether this is common/idiomatic to write functions that return impl Stream<Item = impl Future<Output = x>>?

I haven't seen it in other projects, but maybe I didn't look deep enough.

Thank you.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed