Trait web_thread::web::ScopeExt

source ·
pub trait ScopeExt<'scope> {
    // Required methods
    fn spawn_async<F1, F2, T>(
        &'scope self,
        f: F1,
    ) -> ScopedJoinHandle<'scope, T>
       where F1: 'scope + FnOnce() -> F2 + Send,
             F2: 'scope + Future<Output = T>,
             T: 'scope + Send;
    fn spawn_with_message<F1, F2, T, M>(
        &'scope self,
        f: F1,
        message: M,
    ) -> ScopedJoinHandle<'scope, T>
       where F1: 'scope + FnOnce(M) -> F2 + Send,
             F2: 'scope + Future<Output = T>,
             T: 'scope + Send,
             M: 'scope + MessageSend;
}
Available on Web only.
Expand description

Web-specific extension for web_thread::Scope.

Required Methods§

source

fn spawn_async<F1, F2, T>(&'scope self, f: F1) -> ScopedJoinHandle<'scope, T>
where F1: 'scope + FnOnce() -> F2 + Send, F2: 'scope + Future<Output = T>, T: 'scope + Send,

Async version of Scope::spawn().

§Notes

Commonly a long-running thread is used by sending messages or tasks to it and blocking it when there is no work. Unfortunately this is often undesirable on the Web platform as it prevents yielding to the event loop.

Therefor being able to await the next task instead of blocking the thread is essential to build long-running threads on the Web platform.

§Panics

If the main thread does not support spawning threads, see has_spawn_support().

§Example
use web_thread::web::{self, ScopeExt};

let (sender, receiver) = async_channel::unbounded::<usize>();

web::scope_async(move |scope| async move {
	scope.spawn_async(move || async move {
		while let Ok(message) = receiver.recv().await {
			web_sys::console::log_1(&message.into());
		}
	});
});

for message in 0..10 {
	sender.try_send(message).unwrap();
}
source

fn spawn_with_message<F1, F2, T, M>( &'scope self, f: F1, message: M, ) -> ScopedJoinHandle<'scope, T>
where F1: 'scope + FnOnce(M) -> F2 + Send, F2: 'scope + Future<Output = T>, T: 'scope + Send, M: 'scope + MessageSend,

Available on crate feature message only.

ScopeExt::spawn_async() with message.

For a more complete documentation see ScopeExt::spawn_async() and spawn_with_message().

§Panics
  • If the main thread does not support spawning threads, see has_spawn_support().
  • If message was unable to be cloned.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<'scope> ScopeExt<'scope> for Scope<'scope, '_>