diff options
Diffstat (limited to 'learn_22/src')
| -rw-r--r-- | learn_22/src/event.rs | 53 | ||||
| -rw-r--r-- | learn_22/src/lib.rs | 1 | ||||
| -rw-r--r-- | learn_22/src/main.rs | 3 |
3 files changed, 57 insertions, 0 deletions
diff --git a/learn_22/src/event.rs b/learn_22/src/event.rs new file mode 100644 index 0000000..b9fb3bc --- /dev/null +++ b/learn_22/src/event.rs @@ -0,0 +1,53 @@ +use std::collections::BTreeMap; + +type SubscriptionId = u32; + +type Listener = Box<dyn FnMut(&Event) + 'static>; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + UserCreated { id: u64, name: String }, + UserDeleted { id: u64 }, + MessageReceived { from: u64, text: String }, +} + +pub struct EventBus { + listeners: BTreeMap<SubscriptionId, Listener>, + subscription_id: SubscriptionId, +} + +impl EventBus { + pub fn new() -> Self { + Self { + listeners: BTreeMap::new(), + subscription_id: 0, + } + } + + pub fn subscribe<F>(&mut self, callback: F) -> SubscriptionId + where + F: FnMut(&Event) + 'static, + { + let subscription_id = self.subscription_id; + self.listeners.insert(subscription_id, Box::new(callback)); + self.subscription_id += 1; + subscription_id + } + + pub fn unsubscribe(&mut self, id: SubscriptionId) -> bool { + match self.listeners.remove(&id) { + Some(_) => true, + _ => false, + } + } + + pub fn publish(&mut self, event: Event) { + for (_, callback) in &mut self.listeners { + callback(&event); + } + } + + pub fn subscriber_count(&self) -> usize { + self.listeners.len() + } +} diff --git a/learn_22/src/lib.rs b/learn_22/src/lib.rs new file mode 100644 index 0000000..53f1126 --- /dev/null +++ b/learn_22/src/lib.rs @@ -0,0 +1 @@ +pub mod event; diff --git a/learn_22/src/main.rs b/learn_22/src/main.rs new file mode 100644 index 0000000..db91fc6 --- /dev/null +++ b/learn_22/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + () +} |
