use std::sync::Arc;
use hello_egui_utils::MaybeSend;
use parking_lot::Mutex;
use crate::{UiInbox, UiInboxSender};
#[derive(Debug, Clone)]
pub struct Broadcast<T> {
senders: Arc<Mutex<Vec<UiInboxSender<T>>>>,
}
impl<T> Default for Broadcast<T> {
fn default() -> Self {
Self {
senders: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl<T> Broadcast<T> {
pub fn new() -> Self {
Self::default()
}
pub fn subscribe(&self) -> BroadcastReceiver<T> {
let (tx, rx) = UiInbox::channel();
self.senders.lock().push(tx);
rx
}
#[allow(clippy::needless_pass_by_value)]
pub fn send(&self, message: T)
where
T: Clone + MaybeSend + 'static,
{
let mut senders = self.senders.lock();
senders.retain(|tx| tx.send(message.clone()).is_ok());
}
}
pub type BroadcastReceiver<T> = UiInbox<T>;