use crate::{event_bus_internal::EventBusInternal, EventBus};
use std::sync::Arc;
#[cfg(test)]
mod tests;
pub struct EventEmitter<ContentType, TopicId: std::cmp::PartialEq + Clone> {
event_bus: Option<Arc<EventBusInternal<ContentType, TopicId>>>,
source_id: u64,
}
impl<ContentType, TopicId: std::cmp::PartialEq + Clone> EventEmitter<ContentType, TopicId> {
pub fn with_bus(bus: &EventBus<ContentType, TopicId>) -> Self {
Self {
event_bus: Some(bus.get_internal()),
source_id: 0,
}
}
pub fn new() -> Self {
Self {
event_bus: None,
source_id: 0,
}
}
pub fn set_bus(
&mut self,
bus: &EventBus<ContentType, TopicId>,
source_id: Option<u64>,
) -> Result<(), &'static str> {
let internal_bus = bus.get_internal();
let id = internal_bus.register_publisher(source_id)?;
self.source_id = id;
self.event_bus = Some(bus.get_internal());
Ok(())
}
pub fn publish(&mut self, content: ContentType, topic_id: Option<TopicId>) {
match &mut self.event_bus {
None => {
panic!("Publisher has no bus");
}
Some(bus) => {
bus.publish(content, topic_id, self.source_id);
}
}
}
}
pub trait Publisher<ContentType, TopicId: std::cmp::PartialEq + Clone> {
fn get_mut_emitter(&mut self) -> &mut EventEmitter<ContentType, TopicId>;
fn publish(&mut self, content: ContentType, topic_id: Option<TopicId>) {
self.get_mut_emitter().publish(content, topic_id);
}
}