events, observers & happy new year 🎆
This commit is contained in:
@@ -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 +1,2 @@
|
||||
pub mod enum_dispatch;
|
||||
pub mod observer;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user