Skip to content

Commit

Permalink
Merge pull request #2497 from iced-rs/stream-try-channel
Browse files Browse the repository at this point in the history
Introduce `stream::try_channel` helper
  • Loading branch information
hecrj authored Jul 11, 2024
2 parents 70f44a6 + 4ce2a20 commit d894434
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions futures/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,24 @@ where

stream::select(receiver, runner)
}

/// Creates a new [`Stream`] that produces the items sent from a [`Future`]
/// that can fail to the [`mpsc::Sender`] provided to the closure.
pub fn try_channel<T, E, F>(
size: usize,
f: impl FnOnce(mpsc::Sender<T>) -> F,
) -> impl Stream<Item = Result<T, E>>
where
F: Future<Output = Result<(), E>>,
{
let (sender, receiver) = mpsc::channel(size);

let runner = stream::once(f(sender)).filter_map(|result| async {
match result {
Ok(()) => None,
Err(error) => Some(Err(error)),
}
});

stream::select(receiver.map(Ok), runner)
}

0 comments on commit d894434

Please sign in to comment.