Skip to content

Commit

Permalink
Add a has_changed function to tokio::sync::watch::Receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
elichai committed Dec 24, 2021
1 parent 78e0f0b commit 1a380a4
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions tokio/src/sync/watch.rs
Expand Up @@ -318,6 +318,41 @@ impl<T> Receiver<T> {
Ref { inner }
}

/// Checks if the value had changed, without marking the newest value as seen.
/// # Examples
///
/// ```
/// use tokio::sync::watch;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = watch::channel("hello");
///
/// tx.send("goodbye").unwrap();
///
/// assert!(rx.has_changed().unwrap());
/// assert_eq!(*rx.borrow_and_update(), "goodbye");
///
/// // The value has been marked as seen
/// assert!(!rx.has_changed().unwrap());
///
/// drop(tx);
/// // The `tx` handle has been dropped
/// assert!(rx.has_changed().is_err());
/// }
/// ```
pub fn has_changed(&self) -> Result<bool, error::RecvError> {
// Load the version from the state
let state = self.shared.state.load();
if state.is_closed() {
// All receivers have dropped.
return Err(error::RecvError(()));
}
let new_version = state.version();

Ok(self.version != new_version)
}

/// Waits for a change notification, then marks the newest value as seen.
///
/// If the newest value in the channel has not yet been marked seen when
Expand Down

0 comments on commit 1a380a4

Please sign in to comment.