events, observers & happy new year 🎆

This commit is contained in:
Théo Monnom
2023-01-01 22:38:27 +01:00
parent b36d721a5d
commit 87dc42b09e
12 changed files with 507 additions and 204 deletions
+2
View File
@@ -6,3 +6,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
parking_lot = "0.12.1"
tokio = { version = "1", features = ["full"] }
+1
View File
@@ -1 +1,2 @@
pub mod enum_dispatch;
pub mod observer;
+39
View File
@@ -0,0 +1,39 @@
// Really basic implementation of the observer pattern using mpsc channels.
// Currently unbounded channels
use tokio::sync::mpsc;
#[derive(Debug)]
pub struct Dispatcher<T>
where
T: Clone,
{
senders: Vec<mpsc::UnboundedSender<T>>,
}
impl<T> Default for Dispatcher<T>
where
T: Clone,
{
fn default() -> Self {
Self {
senders: Default::default(),
}
}
}
impl<T> Dispatcher<T>
where
T: Clone,
{
pub fn register(&mut self) -> mpsc::UnboundedReceiver<T> {
let (tx, rx) = mpsc::unbounded_channel();
self.senders.push(tx);
rx
}
pub fn dispatch(&mut self, msg: &T) {
self.senders
.retain(|sender| sender.send(msg.clone()).is_err());
}
}