Skip to content

Commit a68f5ee

Browse files
authored
feat: Add a way to get the current number of listeners
1 parent 5f5135e commit a68f5ee

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/lib.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,42 @@ impl<T> Event<T> {
479479

480480
inner
481481
}
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+
}
482518
}
483519

484520
impl Event<()> {

src/std.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl<T> List<T> {
4444
notified: 0,
4545
}))
4646
}
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.
4848
pub fn total_listeners(&self) -> Result<usize, &str> {
4949
match self.0.try_lock() {
5050
Ok(mutex) => {
@@ -54,6 +54,14 @@ impl<T> List<T> {
5454
Err(_) => Err("<locked>"),
5555
}
5656
}
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+
}
5765
}
5866

5967
impl<T> crate::Inner<T> {

0 commit comments

Comments
 (0)