File tree Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change @@ -479,6 +479,42 @@ impl<T> Event<T> {
479
479
480
480
inner
481
481
}
482
+
483
+ /// Return the listener count by acquiring a lock.
484
+ ///
485
+ /// This is just a snapshot of the number of listeners at this point in time.
486
+ /// It is possible for the actual number to change at any point.
487
+ /// The number should only ever be used as a hint.
488
+ /// This is only available when `std` feature is enabled.
489
+ ///
490
+ /// # Examples
491
+ ///
492
+ /// ```
493
+ /// use event_listener::Event;
494
+ ///
495
+ /// let event = Event::new();
496
+ ///
497
+ /// assert_eq!(event.total_listeners(), 0);
498
+ ///
499
+ /// let listener1 = event.listen();
500
+ /// assert_eq!(event.total_listeners(), 1);
501
+ ///
502
+ /// let listener2 = event.listen();
503
+ /// assert_eq!(event.total_listeners(), 2);
504
+ ///
505
+ /// drop(listener1);
506
+ /// drop(listener2);
507
+ /// assert_eq!(event.total_listeners(), 0);
508
+ /// ```
509
+ #[ cfg( feature = "std" ) ]
510
+ #[ inline]
511
+ pub fn total_listeners ( & self ) -> usize {
512
+ if let Some ( inner) = self . try_inner ( ) {
513
+ inner. list . total_listeners_wait ( )
514
+ } else {
515
+ 0
516
+ }
517
+ }
482
518
}
483
519
484
520
impl Event < ( ) > {
Original file line number Diff line number Diff line change @@ -44,7 +44,7 @@ impl<T> List<T> {
44
44
notified : 0 ,
45
45
} ) )
46
46
}
47
- // Accessor method because fields are private, not sure how to go around it
47
+ // Accessor method because fields are private, not sure how to go around it.
48
48
pub fn total_listeners ( & self ) -> Result < usize , & str > {
49
49
match self . 0 . try_lock ( ) {
50
50
Ok ( mutex) => {
@@ -54,6 +54,14 @@ impl<T> List<T> {
54
54
Err ( _) => Err ( "<locked>" ) ,
55
55
}
56
56
}
57
+
58
+ // Get the listener count by blocking.
59
+ pub ( crate ) fn total_listeners_wait ( & self ) -> usize {
60
+ match self . 0 . lock ( ) {
61
+ Ok ( mutex) => mutex. len ,
62
+ Err ( err) => panic ! ( "{err}" ) ,
63
+ }
64
+ }
57
65
}
58
66
59
67
impl < T > crate :: Inner < T > {
You can’t perform that action at this time.
0 commit comments