1#[must_use = "the host-event handler is removed when the subscription is dropped"]
2pub struct HostEventSubscription {
3 unsubscribe: Option<Box<dyn FnOnce()>>,
4}
5
6impl HostEventSubscription {
7 #[doc(hidden)]
8 pub fn new(unsubscribe: impl FnOnce() + 'static) -> Self {
9 Self {
10 unsubscribe: Some(Box::new(unsubscribe)),
11 }
12 }
13}
14
15impl Drop for HostEventSubscription {
16 fn drop(&mut self) {
17 if let Some(unsubscribe) = self.unsubscribe.take() {
18 unsubscribe();
19 }
20 }
21}
22
23#[cfg(test)]
24mod tests {
25 use super::*;
26 use std::cell::Cell;
27 use std::rc::Rc;
28
29 #[test]
30 fn dropping_host_event_subscription_runs_unsubscribe_once() {
31 let unsubscribe_count = Rc::new(Cell::new(0));
32 let captured_count = unsubscribe_count.clone();
33 let subscription = HostEventSubscription::new(move || {
34 captured_count.set(captured_count.get() + 1);
35 });
36
37 drop(subscription);
38
39 assert_eq!(unsubscribe_count.get(), 1);
40 }
41}