yew_agent/oneshot/
worker.rs1use super::traits::Oneshot;
2use crate::worker::{HandlerId, Worker, WorkerDestroyHandle, WorkerScope};
3
4pub(crate) enum Message<T>
5where
6 T: Oneshot,
7{
8 Finished {
9 handler_id: HandlerId,
10 output: T::Output,
11 },
12}
13
14pub(crate) struct OneshotWorker<T>
15where
16 T: 'static + Oneshot,
17{
18 running_tasks: usize,
19 destruct_handle: Option<WorkerDestroyHandle<Self>>,
20}
21
22impl<T> Worker for OneshotWorker<T>
23where
24 T: 'static + Oneshot,
25{
26 type Input = T::Input;
27 type Message = Message<T>;
28 type Output = T::Output;
29
30 fn create(_scope: &WorkerScope<Self>) -> Self {
31 Self {
32 running_tasks: 0,
33 destruct_handle: None,
34 }
35 }
36
37 fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message) {
38 let Message::Finished { handler_id, output } = msg;
39
40 self.running_tasks -= 1;
41
42 scope.respond(handler_id, output);
43
44 if self.running_tasks == 0 {
45 self.destruct_handle = None;
46 }
47 }
48
49 fn received(&mut self, scope: &WorkerScope<Self>, input: Self::Input, handler_id: HandlerId) {
50 self.running_tasks += 1;
51
52 scope.send_future(async move {
53 let output = T::create(input).await;
54
55 Message::Finished { handler_id, output }
56 });
57 }
58
59 fn destroy(&mut self, _scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) {
60 if self.running_tasks > 0 {
61 self.destruct_handle = Some(destruct);
62 }
63 }
64}