pub fn try_async_stream<T, E, F, U>(generator: F) -> TryAsyncStream<T, E, U>
Expand description
Create an asynchronous Stream
from a fallible asynchronous generator function.
Usage is similar to crate::async_stream
, however the future returned by generator
is assumed to return
Result<(), E>
instead of ()
.
use std::{io, net::SocketAddr};
use async_stream_lite::try_async_stream;
use futures::stream::Stream;
use tokio::net::{TcpListener, TcpStream};
fn bind_and_accept(addr: SocketAddr) -> impl Stream<Item = io::Result<TcpStream>> {
try_async_stream(|yielder| async move {
let mut listener = TcpListener::bind(addr).await?;
loop {
let (stream, addr) = listener.accept().await?;
println!("received on {addr:?}");
yielder.r#yield(stream).await;
}
})
}
The resulting stream yields Result<T, E>
. The yielder function will cause the stream to yield Ok(T)
. When an
error is encountered, the stream yields Err(E)
and is subsequently terminated.