Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sync::watch::Sender::subscribe public #3800

Merged
merged 5 commits into from
Aug 19, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions tokio/src/sync/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,13 +409,35 @@ impl<T> Sender<T> {
debug_assert_eq!(0, self.shared.ref_count_rx.load(Relaxed));
}

cfg_signal_internal! {
pub(crate) fn subscribe(&self) -> Receiver<T> {
let shared = self.shared.clone();
let version = shared.version.load(SeqCst);
/// Creates a new [`Receiver`] handle that will receive values sent **after**
/// this call to `subscribe`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Creates a new [`Receiver`] handle that will receive values sent **after**
/// this call to `subscribe`.
/// Creates a new [`Receiver`] handle that will receive values sent after
/// this call to `subscribe`.

///
/// # Examples
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a note about how this method behaves if the channel is closed when you call it? And preferably also add a test for that behavior?

///
/// ```
/// use tokio::sync::watch;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, _rx) = watch::channel(0u64);
///
/// tx.send(5).unwrap();
///
/// let mut rx = tx.subscribe();
/// // A new Receiver will immediately see the latest value.
/// assert_eq!(5, *rx.borrow());
///
/// tx.send(100).unwrap();
///
/// rx.changed().await.unwrap();
/// assert_eq!(100, *rx.borrow());
/// }
/// ```
pub fn subscribe(&self) -> Receiver<T> {
let shared = self.shared.clone();
let version = shared.version.load(SeqCst);

Receiver::from_shared(version, shared)
}
Receiver::from_shared(version, shared)
}

/// Returns the number of receivers that currently exist
Expand Down