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

add receiver_count to sync::watch::Sender #3729

Merged
merged 1 commit into from May 15, 2021
Merged

add receiver_count to sync::watch::Sender #3729

merged 1 commit into from May 15, 2021

Conversation

soerenmeier
Copy link
Contributor

Add a method to sync::watch::Sender to be able to check how many receivers currently exist.

Motivation

I wanted to be able to get a new Receiver from a Sender and stop sending if there aren't any receivers. To get a new Receiver however i need to store one (a Sender cannot create a Receiver). Which makes it impossible with the current methods to detect if the channel has no active receivers left.

Example

struct Sender<T> {
    tx: watch::Sender<T>,
    rx: watch::Receiver<T>
}

impl<T> Sender<T> {
    pub fn subscribe(&self) -> watch::Receiver<T> {
       self.rx.clone()
   }
    /// Returns Err(()) if no receivers exist
    pub fn send(&mut self, msg: T) -> Result<(), ()> {
        if self.tx.receiver_count() <= 1 {
            Err(())
        } else {
            self.sender.send(msg).unwrap();
            Ok(())
        }
    }
}

Solution

Adding receiver_count seams to be the smallest change that solves my problem.
However if your open to it and feel that watch::Sender could benefit from subscribe i can add that to this PR.

@Darksonn Darksonn added A-tokio Area: The main tokio crate M-sync Module: tokio/sync labels Apr 25, 2021
@soerenmeier
Copy link
Contributor Author

As it seems, I'm probably not the only one wanting watch::Sender::subscribe see #3757.
Would it be possible to expose Sender::subscribe since it's already implemented as @arthurprs pointed out.

pub(crate) fn subscribe(&self) -> Receiver<T> {
let shared = self.shared.clone();
let version = shared.version.load(SeqCst);
Receiver::from_shared(version, shared)
}

Or are there any concerns exposing this?

@Darksonn
Copy link
Contributor

I don't have time to review until friday.

Copy link
Contributor

@Darksonn Darksonn left a comment

Choose a reason for hiding this comment

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

This seems fine to me.

@Darksonn Darksonn merged commit 652f0ae into tokio-rs:master May 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio Area: The main tokio crate M-sync Module: tokio/sync
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants