feat: Add a way to get the current number of listeners
This commit is contained in:
parent
5f5135ed81
commit
a68f5ee1b0
36
src/lib.rs
36
src/lib.rs
|
@ -479,6 +479,42 @@ impl<T> Event<T> {
|
|||
|
||||
inner
|
||||
}
|
||||
|
||||
/// Return the listener count by acquiring a lock.
|
||||
///
|
||||
/// This is just a snapshot of the number of listeners at this point in time.
|
||||
/// It is possible for the actual number to change at any point.
|
||||
/// The number should only ever be used as a hint.
|
||||
/// This is only available when `std` feature is enabled.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use event_listener::Event;
|
||||
///
|
||||
/// let event = Event::new();
|
||||
///
|
||||
/// assert_eq!(event.total_listeners(), 0);
|
||||
///
|
||||
/// let listener1 = event.listen();
|
||||
/// assert_eq!(event.total_listeners(), 1);
|
||||
///
|
||||
/// let listener2 = event.listen();
|
||||
/// assert_eq!(event.total_listeners(), 2);
|
||||
///
|
||||
/// drop(listener1);
|
||||
/// drop(listener2);
|
||||
/// assert_eq!(event.total_listeners(), 0);
|
||||
/// ```
|
||||
#[cfg(feature = "std")]
|
||||
#[inline]
|
||||
pub fn total_listeners(&self) -> usize {
|
||||
if let Some(inner) = self.try_inner() {
|
||||
inner.list.total_listeners_wait()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Event<()> {
|
||||
|
|
10
src/std.rs
10
src/std.rs
|
@ -44,7 +44,7 @@ impl<T> List<T> {
|
|||
notified: 0,
|
||||
}))
|
||||
}
|
||||
// Accessor method because fields are private, not sure how to go around it
|
||||
// Accessor method because fields are private, not sure how to go around it.
|
||||
pub fn total_listeners(&self) -> Result<usize, &str> {
|
||||
match self.0.try_lock() {
|
||||
Ok(mutex) => {
|
||||
|
@ -54,6 +54,14 @@ impl<T> List<T> {
|
|||
Err(_) => Err("<locked>"),
|
||||
}
|
||||
}
|
||||
|
||||
// Get the listener count by blocking.
|
||||
pub(crate) fn total_listeners_wait(&self) -> usize {
|
||||
match self.0.lock() {
|
||||
Ok(mutex) => mutex.len,
|
||||
Err(err) => panic!("{err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> crate::Inner<T> {
|
||||
|
|
Loading…
Reference in New Issue