actm/types/
waiter.rs

1//! Utility type for waiting on an event to happen, possibly across a sync/async boundary.
2
3use flume::{Receiver, Sender};
4
5/// Utility type for waiting on an event to happen, possibly across a sync/async boundary.
6pub struct Waiter {
7    /// Internal channel
8    recv: Receiver<()>,
9}
10
11/// Utility type for signaling an event has happend, possibly across a sync/async boundary.
12pub struct Trigger {
13    /// Internal channel
14    send: Sender<()>,
15}
16
17impl Waiter {
18    /// Create a new `Waiter`/`Trigger` pair
19    pub fn new() -> (Waiter, Trigger) {
20        let (send, recv) = flume::bounded(1);
21        (Waiter { recv }, Trigger { send })
22    }
23
24    /// Asynchronously wait for the event, returning `true` if the event happened, or `false` if the
25    /// `Trigger` was dropped before completion
26    pub async fn wait(self) -> bool {
27        self.recv.recv_async().await.is_ok()
28    }
29
30    /// Synchronously wait for the event, returning `true` if the event happened, or `false` if the
31    /// `Trigger` was dropped before completion
32    pub fn wait_sync(self) -> bool {
33        self.recv.recv().is_ok()
34    }
35}
36
37impl Trigger {
38    /// Consume the trigger and signal the waiter
39    pub fn trigger(self) {
40        let _ = self.send.send(());
41    }
42}