The #[stream] attribute allows you to create streams using coroutine-like syntax with the yield expression.
On async fn
When using #[stream] on an async fn, you must specify the item type using the item = ... argument.
- Use
yield <value> to output values from the stream. - Use
return to early exit the stream.
On async blocks
#[stream] can also be applied to async blocks. Unlike functions, #[stream] on an async block does not require the item argument, though it may require additional type annotations.
Integration with #[for_await]
If you only use #[for_await] inside a #[stream] function, you do not need to explicitly import for_await as it is built-in.
#![feature(coroutines)]
use futures::stream::Stream;
use futures_async_stream::stream;
// Returns a stream of i32
#[stream(item = i32)]
async fn foo(stream: impl Stream<Item = String>) {
#[for_await]
for x in stream {
yield x.parse().unwrap();
}
}
// Using on an async block
fn foo_block() -> impl Stream<Item = i32> {
#[stream]
async move {
for i in 0..10 {
yield i;
}
}
}