This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew_agent/reactor/
spawner.rs

1use serde::de::Deserialize;
2use serde::ser::Serialize;
3
4use super::bridge::ReactorBridge;
5use super::scope::ReactorScoped;
6use super::traits::Reactor;
7use super::worker::ReactorWorker;
8use crate::codec::{Bincode, Codec};
9use crate::worker::WorkerSpawner;
10
11/// A spawner to create oneshot workers.
12#[derive(Debug, Default)]
13pub struct ReactorSpawner<R, CODEC = Bincode>
14where
15    R: Reactor + 'static,
16    CODEC: Codec,
17{
18    inner: WorkerSpawner<ReactorWorker<R>, CODEC>,
19}
20
21impl<R, CODEC> ReactorSpawner<R, CODEC>
22where
23    R: Reactor + 'static,
24    CODEC: Codec,
25{
26    /// Creates a ReactorSpawner.
27    pub const fn new() -> Self {
28        Self {
29            inner: WorkerSpawner::<ReactorWorker<R>, CODEC>::new(),
30        }
31    }
32
33    /// Sets a new message encoding.
34    pub const fn encoding<C>(&self) -> ReactorSpawner<R, C>
35    where
36        C: Codec,
37    {
38        ReactorSpawner {
39            inner: WorkerSpawner::<ReactorWorker<R>, C>::new(),
40        }
41    }
42
43    /// Indicates that [`spawn`](WorkerSpawner#method.spawn) should expect a
44    /// `path` to a loader shim script (e.g. when using Trunk, created by using
45    /// the [`data-loader-shim`](https://trunkrs.dev/assets/#link-asset-types)
46    /// asset type) and one does not need to be generated. `false` by default.
47    pub fn with_loader(mut self, with_loader: bool) -> Self {
48        self.inner.with_loader(with_loader);
49        self
50    }
51
52    /// Determines whether the worker will be spawned with
53    /// [`options.type`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#type)
54    /// set to `module`. `true` by default.
55    ///
56    /// This option should be un-set if the worker was created with the
57    /// `--target no-modules` flag of `wasm-bindgen`. If using Trunk, see the
58    /// [`data-bindgen-target`](https://trunkrs.dev/assets/#link-asset-types)
59    /// asset type.
60    pub fn as_module(mut self, as_module: bool) -> Self {
61        self.inner.as_module(as_module);
62
63        self
64    }
65
66    /// Spawns a reactor worker.
67    pub fn spawn(mut self, path: &str) -> ReactorBridge<R>
68    where
69        <R::Scope as ReactorScoped>::Input: Serialize + for<'de> Deserialize<'de>,
70        <R::Scope as ReactorScoped>::Output: Serialize + for<'de> Deserialize<'de>,
71    {
72        let rx = ReactorBridge::register_callback(&mut self.inner);
73
74        let inner = self.inner.spawn(path);
75
76        ReactorBridge::new(inner, rx)
77    }
78}