1use crate::{event_bus_internal::EventBusInternal, EventBus};
13use std::sync::Arc;
14
15#[cfg(test)]
16mod tests;
17
18pub struct EventEmitter<ContentType, TopicId: std::cmp::PartialEq + Clone> {
21 event_bus: Option<Arc<EventBusInternal<ContentType, TopicId>>>,
22 source_id: u64,
23}
24
25impl<ContentType, TopicId: std::cmp::PartialEq + Clone> EventEmitter<ContentType, TopicId> {
26 pub fn with_bus(bus: &EventBus<ContentType, TopicId>) -> Self {
27 Self {
28 event_bus: Some(bus.get_internal()),
29 source_id: 0,
30 }
31 }
32
33 pub fn new() -> Self {
34 Self {
35 event_bus: None,
36 source_id: 0,
37 }
38 }
39
40 pub fn set_bus(
43 &mut self,
44 bus: &EventBus<ContentType, TopicId>,
45 source_id: Option<u64>,
46 ) -> Result<(), &'static str> {
47 let internal_bus = bus.get_internal();
48 let id = internal_bus.register_publisher(source_id)?;
49
50 self.source_id = id;
51 self.event_bus = Some(bus.get_internal());
52 Ok(())
53 }
54
55 pub fn publish(&mut self, content: ContentType, topic_id: Option<TopicId>) {
58 match &mut self.event_bus {
59 None => {
60 panic!("Publisher has no bus");
61 }
62 Some(bus) => {
63 bus.publish(content, topic_id, self.source_id);
64 }
65 }
66 }
67}
68
69pub trait Publisher<ContentType, TopicId: std::cmp::PartialEq + Clone> {
72 fn get_mut_emitter(&mut self) -> &mut EventEmitter<ContentType, TopicId>;
74
75 fn publish(&mut self, content: ContentType, topic_id: Option<TopicId>) {
78 self.get_mut_emitter().publish(content, topic_id);
79 }
80}