Skip to main content

lgui_core/events/
subscription.rs

1use std::sync::{Arc, Weak};
2
3use super::bus::EventBusInner;
4
5pub struct EventSubscription {
6    bus: Weak<EventBusInner>,
7    key: Arc<str>,
8    id: u64,
9}
10
11impl EventSubscription {
12    pub(super) fn new(bus: &Arc<EventBusInner>, key: Arc<str>, id: u64) -> Self {
13        Self {
14            bus: Arc::downgrade(bus),
15            key,
16            id,
17        }
18    }
19}
20
21impl Drop for EventSubscription {
22    fn drop(&mut self) {
23        let Some(bus) = self.bus.upgrade() else {
24            return;
25        };
26        let mut topics = bus.topics.lock().expect("event bus poisoned");
27        let remove_topic = topics.get_mut(self.key.as_ref()).is_some_and(|topic| {
28            topic.listeners.remove(&self.id);
29            topic.listeners.is_empty()
30        });
31        if remove_topic {
32            topics.remove(self.key.as_ref());
33        }
34    }
35}