From a761448858521d11dc646e2ef5217e9e06628932 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 29 Nov 2023 00:14:27 +0100 Subject: Implement `command::channel` helper It is analogous to `subscription::channel`. --- runtime/src/command.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'runtime/src/command.rs') diff --git a/runtime/src/command.rs b/runtime/src/command.rs index b942f3ce..f70da915 100644 --- a/runtime/src/command.rs +++ b/runtime/src/command.rs @@ -7,6 +7,7 @@ use crate::core::widget; use crate::futures::futures; use crate::futures::MaybeSend; +use futures::channel::mpsc; use futures::Stream; use std::fmt; use std::future::Future; @@ -118,3 +119,23 @@ impl fmt::Debug for Command { command.fmt(f) } } + +/// Creates a [`Command`] that produces the `Message`s published from a [`Future`] +/// to an [`mpsc::Sender`] with the given bounds. +pub fn channel( + size: usize, + f: impl FnOnce(mpsc::Sender) -> Fut + MaybeSend + 'static, +) -> Command +where + Fut: Future + MaybeSend + 'static, + Message: 'static + MaybeSend, +{ + use futures::future; + use futures::stream::{self, StreamExt}; + + let (sender, receiver) = mpsc::channel(size); + + let runner = stream::once(f(sender)).filter_map(|_| future::ready(None)); + + Command::single(Action::Stream(Box::pin(stream::select(receiver, runner)))) +} -- cgit