diff --git a/packages/yew/src/html/component/scope.rs b/packages/yew/src/html/component/scope.rs index 42fb6e367c9..89645698e28 100644 --- a/packages/yew/src/html/component/scope.rs +++ b/packages/yew/src/html/component/scope.rs @@ -7,6 +7,8 @@ use std::ops::Deref; use std::rc::Rc; use std::{fmt, iter}; +use futures::{Stream, StreamExt}; + #[cfg(any(feature = "csr", feature = "ssr"))] use super::lifecycle::ComponentState; use super::BaseComponent; @@ -236,6 +238,35 @@ impl Scope { spawn_local(js_future); } + /// This method asynchronously awaits a [`Stream`] that returns a series of messages and sends + /// them to the linked component. + /// + /// # Panics + /// If the stream panics, then the promise will not resolve, and will leak. + /// + /// # Note + /// + /// This method will not notify the component when the stream has been fully exhausted. If + /// you want this feature, you can add an EOF message variant for your component and use + /// [`StreamExt::chain`] and [`stream::once`] to chain an EOF message to the original stream. + /// If your stream is produced by another crate, you can use [`StreamExt::map`] to transform + /// the stream's item type to the component message type. + pub fn send_stream(&self, stream: S) + where + M: Into, + S: Stream + 'static, + { + let link = self.clone(); + let js_future = async move { + futures::pin_mut!(stream); + while let Some(msg) = stream.next().await { + let message: COMP::Message = msg.into(); + link.send_message(message); + } + }; + spawn_local(js_future); + } + /// Returns the linked component if available pub fn get_component(&self) -> Option + '_> { self.arch_get_component()