Skip to main content

binary_options_tools_core_pre/
signals.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::Arc;
3use tokio::sync::Notify;
4
5#[derive(Clone, Default, Debug)]
6pub struct Signals {
7    is_connected: Arc<AtomicBool>,
8    connected_notify: Arc<Notify>,
9    disconnected_notify: Arc<Notify>,
10}
11
12impl Signals {
13    /// Call this when a connection is established.
14    pub fn set_connected(&self) {
15        self.is_connected.store(true, Ordering::SeqCst);
16        self.connected_notify.notify_waiters();
17    }
18
19    /// Call this when a disconnection occurs.
20    pub fn set_disconnected(&self) {
21        self.is_connected.store(false, Ordering::SeqCst);
22        self.disconnected_notify.notify_waiters();
23    }
24
25    /// Check current connection state.
26    pub fn is_connected(&self) -> bool {
27        self.is_connected.load(Ordering::SeqCst)
28    }
29
30    /// Wait for the next connection event.
31    pub async fn wait_connected(&self) {
32        // Only wait if not already connected
33        if !self.is_connected() {
34            self.connected_notify.notified().await;
35        }
36    }
37
38    /// Wait for the next disconnection event.
39    pub async fn wait_disconnected(&self) {
40        // Only wait if currently connected
41        if self.is_connected() {
42            self.disconnected_notify.notified().await;
43        }
44    }
45}