forked from nintha/river
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventbus.rs
More file actions
57 lines (48 loc) · 1.62 KB
/
Copy patheventbus.rs
File metadata and controls
57 lines (48 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use smol::channel::{Receiver, Sender};
pub struct EventBus<E> {
label: String,
incr_val: AtomicCell<u64>,
tx_map: DashMap<u64, Sender<E>>,
}
impl<E: 'static + Clone> EventBus<E> {
pub fn with_label(label: String) -> Self {
Self {
label,
incr_val: Default::default(),
tx_map: Default::default(),
}
}
pub async fn publish(&self, val: E) {
let mut dropped_senders: Vec<u64> = vec![];
let mut keys: Vec<u64> = self.tx_map.iter().map(|x| x.key().to_owned()).collect();
let last_key = keys.pop();
for key in keys {
if let Some(entry) = self.tx_map.get(&key) {
if let Err(_) = entry.send(val.clone()).await {
dropped_senders.push(key);
}
}
}
// 最后一个元素可以直接发送,减少一次clone
if let Some(key) = last_key {
if let Some(entry) = self.tx_map.get(&key) {
if let Err(_) = entry.send(val).await {
dropped_senders.push(key);
}
}
}
for key in dropped_senders.iter() {
self.tx_map.remove(key);
log::info!("[EventBus][{}] remove receiver {}", self.label, key);
}
}
pub fn register_receiver(&self) -> Receiver<E> {
let (tx, rx) = smol::channel::unbounded();
let key = self.incr_val.fetch_add(1);
self.tx_map.insert(key, tx);
log::info!("[EventBus][{}] add receiver {}", self.label, key);
rx
}
}