genawaiter_try_stream/
lib.rs

1use std::sync::Arc;
2
3use futures_core::{Stream, TryFuture};
4use genawaiter::sync::Gen;
5
6pub struct Co<T, E>(Arc<genawaiter::sync::Co<Result<T, E>>>);
7
8impl<T, E> Co<T, E> {
9    pub async fn yield_(&self, value: T) {
10        self.0.yield_(Ok(value)).await
11    }
12}
13
14pub fn try_stream<T: Send, E: Send, F: Send + TryFuture<Output = Result<(), E>>>(
15    f: impl Send + FnOnce(Co<T, E>) -> F,
16) -> impl Unpin + Send + Stream<Item = Result<T, E>> {
17    Gen::new(async |co| {
18        let co = Arc::new(co);
19        if let Err(e) = f(Co(co.clone())).await {
20            co.yield_(Err(e)).await;
21        }
22    })
23}