diff options
| author | Brad Clawsie <brad@b7j0c.org> | 2026-11-30 10:58:44 -0600 |
|---|---|---|
| committer | Brad Clawsie <brad@b7j0c.org> | 2026-11-30 10:58:44 -0600 |
| commit | d05cfa7872d6edd0a1b6bd6a9119f7d0e9899660 (patch) | |
| tree | 58d0983f028e534a799ae3b6fd554792602b85a9 /learn_22/src/event.rs | |
| parent | dfab0cabdac6603176ab4a5ec58e56d535ceb93b (diff) | |
feat: learn_22
commit 70bcd610ff5eaa3684aaea97938344c53d3eb3e1
Author: Brad Clawsie <brad@b7j0c.org>
Date: Mon Nov 30 10:53:34 2026 -0600
feat: learn_22
commit b6edc59df72940dd7490febb50c69e0b10e19b54
Author: Brad Clawsie <brad@b7j0c.org>
Date: Mon Nov 30 09:36:24 2026 -0600
wip: learn_22
commit fdc8b9e606688cac964822220c8610347b05c644
Author: Brad Clawsie <brad@b7j0c.org>
Date: Sun Nov 29 14:46:10 2026 -0600
wip: learn_22
commit 73fa6541d47995adf25a2cbc82f2b2feae69488d
Author: Brad Clawsie <brad@b7j0c.org>
Date: Sun Nov 29 14:30:29 2026 -0600
wip: learn_22
commit 57398e51bbd90024ebd1f7e6a25ca4432fd2e074
Author: Brad Clawsie <brad@b7j0c.org>
Date: Wed Nov 25 15:32:21 2026 -0600
wip: learn_22
Diffstat (limited to 'learn_22/src/event.rs')
| -rw-r--r-- | learn_22/src/event.rs | 53 |
1 files changed, 53 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() + } +} |
