pub struct Watch<M: RawMutex, T: Clone> { /* private fields */ }
Expand description
The Watch
is a single-slot signaling primitive that allows multiple (N
) receivers to get
changes to the value. Unlike a Signal
, Watch
supports multiple receivers,
and unlike a PubSubChannel
, Watch
immediately overwrites the previous
value when a new one is sent, without waiting for all receivers to read the previous value.
This makes Watch
particularly useful when a single task updates a value or “state”, and multiple other tasks
need to be notified about changes to this value asynchronously. Receivers may “lose” stale values, as they are
always provided with the latest value.
use embedded_sync::watch::Watch;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
static WATCH: Watch<CriticalSectionRawMutex, u8> = Watch::new();
// Obtain receivers and sender
let mut rcv0 = WATCH.receiver();
let mut rcv1 = WATCH.receiver();
let mut snd = WATCH.sender();
snd.send(10);
// Receive the new value (async or try)
assert_eq!(rcv0.try_changed(), Some(10));
assert_eq!(rcv1.try_changed(), Some(10));
// No update
assert_eq!(rcv0.try_changed(), None);
assert_eq!(rcv1.try_changed(), None);
snd.send(20);
// Using `get` marks the value as seen
assert_eq!(rcv1.try_get(), Some(20));
assert_eq!(rcv1.try_changed(), None);
snd.send(20);
assert_eq!(rcv1.try_get(), Some(20));
assert_eq!(rcv1.try_get(), Some(20));
Implementations§
Source§impl<M: RawMutex, T: Clone> Watch<M, T>
impl<M: RawMutex, T: Clone> Watch<M, T>
Sourcepub fn receiver(&self) -> Receiver<'_, M, T>
pub fn receiver(&self) -> Receiver<'_, M, T>
Try to create a new Receiver
for the Watch
. If the
maximum number of receivers has been reached, None
is returned.
Sourcepub fn get_msg_id(&self) -> u8
pub fn get_msg_id(&self) -> u8
Returns the message ID of the latest message sent to the Watch
.
This counter is monotonic, and is incremented every time a new message is sent.