yew_stdweb/agent/local/
job.rs1use super::*;
2use crate::callback::Callback;
3use std::marker::PhantomData;
4
5const SINGLETON_ID: HandlerId = HandlerId(0, true);
6
7#[allow(missing_debug_implementations)]
9pub struct Job<AGN> {
10 _agent: PhantomData<AGN>,
11}
12
13impl<AGN> Discoverer for Job<AGN>
14where
15 AGN: Agent,
16{
17 type Agent = AGN;
18
19 fn spawn_or_join(callback: Option<Callback<AGN::Output>>) -> Box<dyn Bridge<AGN>> {
20 let callback = callback.expect("Callback required for Job");
21 let scope = AgentScope::<AGN>::new();
22 let responder = CallbackResponder { callback };
23 let agent_link = AgentLink::connect(&scope, responder);
24 let upd = AgentLifecycleEvent::Create(agent_link);
25 scope.send(upd);
26 let upd = AgentLifecycleEvent::Connected(SINGLETON_ID);
27 scope.send(upd);
28 let bridge = JobBridge { scope };
29 Box::new(bridge)
30 }
31}
32
33struct JobBridge<AGN: Agent> {
34 scope: AgentScope<AGN>,
35}
36
37impl<AGN: Agent> Bridge<AGN> for JobBridge<AGN> {
38 fn send(&mut self, msg: AGN::Input) {
39 let upd = AgentLifecycleEvent::Input(msg, SINGLETON_ID);
40 self.scope.send(upd);
41 }
42}
43
44impl<AGN: Agent> Drop for JobBridge<AGN> {
45 fn drop(&mut self) {
46 let upd = AgentLifecycleEvent::Disconnected(SINGLETON_ID);
47 self.scope.send(upd);
48 let upd = AgentLifecycleEvent::Destroy;
49 self.scope.send(upd);
50 }
51}
52
53struct CallbackResponder<AGN: Agent> {
54 callback: Callback<AGN::Output>,
55}
56
57impl<AGN: Agent> Responder<AGN> for CallbackResponder<AGN> {
58 fn respond(&self, id: HandlerId, output: AGN::Output) {
59 assert_eq!(id.raw_id(), SINGLETON_ID.raw_id());
60 self.callback.emit(output);
61 }
62}