use tokio::sync::broadcast;
#[derive(Debug)]
pub(crate) struct Shutdown {
shutdown: bool,
notify: broadcast::Receiver<()>,
}
impl Shutdown {
pub(crate) fn new(notify: broadcast::Receiver<()>) -> Shutdown {
Shutdown {
shutdown: false,
notify,
}
}
pub(crate) fn is_shutdown(&self) -> bool {
self.shutdown
}
pub(crate) async fn recv(&mut self) {
if self.shutdown {
return;
}
let _ = self.notify.recv().await;
self.shutdown = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_shutdown() {
let (notify_shutdown, _) = broadcast::channel(1);
let mut shutdown = Shutdown::new(notify_shutdown.subscribe());
assert!(!shutdown.is_shutdown());
tokio::spawn(async move { notify_shutdown.send(()) });
shutdown.recv().await;
assert!(shutdown.is_shutdown());
shutdown.recv().await;
assert!(shutdown.is_shutdown());
}
}