Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add send_stream method for Scope #2619

Merged
merged 5 commits into from Aug 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/yew/src/html/component/scope.rs
Expand Up @@ -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;
Expand Down Expand Up @@ -236,6 +238,35 @@ impl<COMP: BaseComponent> Scope<COMP> {
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<S, M>(&self, stream: S)
where
M: Into<COMP::Message>,
S: Stream<Item = M> + '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<impl Deref<Target = COMP> + '_> {
self.arch_get_component()
Expand Down