use std::future::Future;
use tokio::task::JoinSet;
use super::stream::{ChangeEvent, Subscription};
pub struct LiveSubscriptionSet {
tasks: JoinSet<()>,
}
impl LiveSubscriptionSet {
pub fn new() -> Self {
Self {
tasks: JoinSet::new(),
}
}
pub fn spawn_forwarder<F>(&mut self, sub: Subscription, mut on_event: F)
where
F: FnMut(&ChangeEvent) + Send + 'static,
{
let mut sub = sub;
self.tasks.spawn(async move {
while let Ok(event) = sub.recv_filtered().await {
on_event(&event);
}
});
}
pub fn spawn_task<F>(&mut self, fut: F)
where
F: Future<Output = ()> + Send + 'static,
{
self.tasks.spawn(fut);
}
pub fn abort_all(&mut self) {
self.tasks.abort_all();
}
pub fn len(&self) -> usize {
self.tasks.len()
}
pub fn is_empty(&self) -> bool {
self.tasks.is_empty()
}
}
impl Default for LiveSubscriptionSet {
fn default() -> Self {
Self::new()
}
}
impl Drop for LiveSubscriptionSet {
fn drop(&mut self) {
self.tasks.abort_all();
}
}