breez_sdk_liquid/
event.rs1use std::collections::HashMap;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use anyhow::Result;
5use log::{debug, info};
6use tokio::sync::{broadcast, RwLock};
7use uuid::Uuid;
8
9use crate::model::{EventListener, SdkEvent};
10
11pub(crate) struct EventManager {
12 listeners: RwLock<HashMap<String, Box<dyn EventListener>>>,
13 notifier: broadcast::Sender<SdkEvent>,
14 is_paused: AtomicBool,
15}
16
17impl EventManager {
18 pub fn new() -> Self {
19 let (notifier, _) = broadcast::channel::<SdkEvent>(100);
20
21 Self {
22 listeners: Default::default(),
23 notifier,
24 is_paused: AtomicBool::new(false),
25 }
26 }
27
28 pub async fn add(&self, listener: Box<dyn EventListener>) -> Result<String> {
29 let id = Uuid::new_v4().to_string();
30 (*self.listeners.write().await).insert(id.clone(), listener);
31 Ok(id)
32 }
33
34 pub async fn remove(&self, id: String) {
35 (*self.listeners.write().await).remove(&id);
36 }
37
38 pub async fn notify(&self, e: SdkEvent) {
39 match self.is_paused.load(Ordering::SeqCst) {
40 true => info!("Event notifications are paused, not emitting event {e:?}"),
41 false => {
42 debug!("Emitting event: {e:?}");
43 let _ = self.notifier.send(e.clone());
44
45 for listener in (*self.listeners.read().await).values() {
46 listener.on_event(e.clone());
47 }
48 }
49 }
50 }
51
52 pub(crate) fn subscribe(&self) -> broadcast::Receiver<SdkEvent> {
53 self.notifier.subscribe()
54 }
55
56 pub(crate) fn pause_notifications(&self) {
57 info!("Pausing event notifications");
58 self.is_paused.store(true, Ordering::SeqCst);
59 }
60
61 pub(crate) fn resume_notifications(&self) {
62 info!("Resuming event notifications");
63 self.is_paused.store(false, Ordering::SeqCst);
64 }
65}