yew_agent/worker/traits.rs
1use super::handler_id::HandlerId;
2use super::registrar::WorkerRegistrar;
3use super::scope::{WorkerDestroyHandle, WorkerScope};
4use super::spawner::WorkerSpawner;
5use crate::traits::{Registrable, Spawnable};
6
7/// Declares the behaviour of a worker.
8pub trait Worker: Sized {
9 /// Update message type.
10 type Message;
11 /// Incoming message type.
12 type Input;
13 /// Outgoing message type.
14 type Output;
15
16 /// Creates an instance of a worker.
17 fn create(scope: &WorkerScope<Self>) -> Self;
18
19 /// Receives an update.
20 ///
21 /// This method is called when the worker send messages to itself via
22 /// [`WorkerScope::send_message`].
23 fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message);
24
25 /// New bridge created.
26 ///
27 /// When a new bridge is created by [`WorkerSpawner::spawn`](crate::WorkerSpawner)
28 /// or [`WorkerBridge::fork`](crate::WorkerBridge::fork),
29 /// the worker will be notified the [`HandlerId`] of the created bridge via this method.
30 fn connected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) {
31 let _scope = scope;
32 let _id = id;
33 }
34
35 /// Receives an input from a connected bridge.
36 ///
37 /// When a bridge sends an input via [`WorkerBridge::send`](crate::WorkerBridge::send), the
38 /// worker will receive the input via this method.
39 fn received(&mut self, scope: &WorkerScope<Self>, msg: Self::Input, id: HandlerId);
40
41 /// Existing bridge destroyed.
42 ///
43 /// When a bridge is dropped, the worker will be notified with this method.
44 fn disconnected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) {
45 let _scope = scope;
46 let _id = id;
47 }
48
49 /// Destroys the current worker.
50 ///
51 /// When all bridges are dropped, the method will be invoked.
52 ///
53 /// This method is provided a destroy handle where when it is dropped, the worker is closed.
54 /// If the worker is closed immediately, then it can ignore the destroy handle.
55 /// Otherwise hold the destroy handle until the clean up task is finished.
56 ///
57 /// # Note
58 ///
59 /// This method will only be called after all bridges are disconnected.
60 /// Attempting to send messages after this method is called will have no effect.
61 fn destroy(&mut self, scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) {
62 let _scope = scope;
63 let _destruct = destruct;
64 }
65}
66
67impl<W> Spawnable for W
68where
69 W: Worker + 'static,
70{
71 type Spawner = WorkerSpawner<Self>;
72
73 fn spawner() -> WorkerSpawner<Self> {
74 WorkerSpawner::new()
75 }
76}
77
78impl<W> Registrable for W
79where
80 W: Worker + 'static,
81{
82 type Registrar = WorkerRegistrar<Self>;
83
84 fn registrar() -> WorkerRegistrar<Self> {
85 WorkerRegistrar::new()
86 }
87}