19
19
20
20
use std:: collections:: HashMap ;
21
21
use std:: fmt;
22
- use std:: marker:: PhantomData ;
23
22
use std:: sync:: atomic:: { AtomicUsize , Ordering } ;
24
23
use std:: sync:: { Arc , Mutex , Weak } ;
25
24
use std:: time:: Duration ;
@@ -60,7 +59,7 @@ struct InnerEventBroker {
60
59
61
60
impl EventBroker {
62
61
/// Subscribes to an event type.
63
- pub fn subscribe < E > ( & self , subscriber : impl EventSubscriber < E > ) -> EventSubscriptionHandle < E >
62
+ pub fn subscribe < E > ( & self , subscriber : impl EventSubscriber < E > ) -> EventSubscriptionHandle
64
63
where E : Event {
65
64
let mut subscriptions = self
66
65
. inner
@@ -84,11 +83,19 @@ impl EventBroker {
84
83
. get_mut :: < EventSubscriptions < E > > ( )
85
84
. expect ( "The subscription map should exist." ) ;
86
85
typed_subscriptions. insert ( subscription_id, subscription) ;
87
-
88
86
EventSubscriptionHandle {
89
87
subscription_id,
90
88
broker : Arc :: downgrade ( & self . inner ) ,
91
- _phantom : PhantomData ,
89
+ drop_me : |subscription_id, broker| {
90
+ let mut subscriptions = broker
91
+ . subscriptions
92
+ . lock ( )
93
+ . expect ( "the lock should not be poisoned" ) ;
94
+ if let Some ( typed_subscriptions) = subscriptions. get_mut :: < EventSubscriptions < E > > ( )
95
+ {
96
+ typed_subscriptions. remove ( & subscription_id) ;
97
+ }
98
+ } ,
92
99
}
93
100
}
94
101
@@ -120,31 +127,20 @@ struct EventSubscription<E> {
120
127
subscriber : Box < dyn EventSubscriber < E > > ,
121
128
}
122
129
123
- #[ derive( Debug ) ]
124
- pub struct EventSubscriptionHandle < E : Event > {
130
+ pub struct EventSubscriptionHandle {
125
131
subscription_id : usize ,
126
132
broker : Weak < InnerEventBroker > ,
127
- _phantom : PhantomData < E > ,
133
+ drop_me : fn ( usize , & InnerEventBroker ) ,
128
134
}
129
135
130
- impl < E > EventSubscriptionHandle < E >
131
- where E : Event
132
- {
136
+ impl EventSubscriptionHandle {
133
137
pub fn cancel ( self ) { }
134
138
}
135
139
136
- impl < E > Drop for EventSubscriptionHandle < E >
137
- where E : Event
138
- {
140
+ impl Drop for EventSubscriptionHandle {
139
141
fn drop ( & mut self ) {
140
142
if let Some ( broker) = self . broker . upgrade ( ) {
141
- let mut subscriptions = broker
142
- . subscriptions
143
- . lock ( )
144
- . expect ( "the lock should not be poisoned" ) ;
145
- if let Some ( typed_subscriptions) = subscriptions. get_mut :: < EventSubscriptions < E > > ( ) {
146
- typed_subscriptions. remove ( & self . subscription_id ) ;
147
- }
143
+ ( self . drop_me ) ( self . subscription_id , & broker) ;
148
144
}
149
145
}
150
146
}
0 commit comments