pubsub_bus/
event_bus.rs

1// *************************************************************************
2//
3// Copyright (c) 2025 Andrei Gramakov. All rights reserved.
4//
5// This file is licensed under the terms of the MIT license.
6// For a copy, see: https://opensource.org/licenses/MIT
7//
8// site:    https://agramakov.me
9// e-mail:  mail@agramakov.me
10//
11// *************************************************************************
12use crate::{event_bus_internal::EventBusInternal, Publisher, Subscriber};
13use std::sync::{Arc, Mutex};
14
15#[cfg(test)]
16mod tests;
17
18/// The Event Bus itself. Add subscribers and publishers to it.
19pub struct EventBus<ContentType, TopicId: std::cmp::PartialEq + Clone> {
20    internal: Arc<EventBusInternal<ContentType, TopicId>>,
21}
22
23impl<ContentType, TopicId: std::cmp::PartialEq + Clone> EventBus<ContentType, TopicId> {
24    pub fn new() -> Self {
25        Self {
26            internal: Arc::new(EventBusInternal::new()),
27        }
28    }
29
30    pub fn add_subscriber_shared(
31        &self,
32        subscriber: Arc<Mutex<dyn Subscriber<ContentType, TopicId>>>,
33    ) {
34        self.internal.add_subscriber_shared(subscriber);
35    }
36
37    pub fn add_subscriber<S>(&self, subscriber: S)
38    where
39        S: Subscriber<ContentType, TopicId> + 'static, // Ensures it can be converted to a trait object
40    {
41        self.internal.add_subscriber(subscriber);
42    }
43
44    /// Add a publisher to the event bus.
45    /// If source_id is None, the publisher will be assigned a unique id.
46    pub fn add_publisher(
47        &self,
48        publisher: &mut dyn Publisher<ContentType, TopicId>,
49        source_id: Option<u64>,
50    ) -> Result<(), &'static str> {
51        publisher.get_mut_emitter().set_bus(self, source_id)
52    }
53
54    pub fn publish(&self, event: ContentType, topic_id: Option<TopicId>, source_id: u64) {
55        self.internal.publish(event, topic_id, source_id);
56    }
57
58    pub fn get_internal(&self) -> Arc<EventBusInternal<ContentType, TopicId>> {
59        self.internal.clone()
60    }
61}