tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
26.94k stars 2.48k forks source link

Add `broadcast::Sender::closed` Future #6649

Open schmidma opened 4 months ago

schmidma commented 4 months ago

Is your feature request related to a problem? Please describe.

I'm always frustrated when I need to determine if all receivers of a broadcast sender are dropped. Currently, the only way to know if all receivers are gone is by either sending to the channel and getting an error, or by checking the number of receivers. However, there is no way to wait for the event of all receivers being dropped, which would enable a sender to end its operation early if no receivers are interested anymore. This feature is already available in the mpsc and oneshot variants of Tokio channels.

Describe the solution you'd like

I would like the broadcast sender to have a closed future. This future would enable the sender to wait for the event when all receivers are dropped. This way, the sender can stop its operation as soon as there are no more receivers interested in its results.

Describe alternatives you've considered

An alternative solution would be continuously checking the number of receivers or attempting to send a message and catching the error if all receivers are closed. However, this approach is inefficient and explicitly waiting for the close event is not possible.

Additional context

Adding this feature will make the broadcast sender more consistent with the mpsc and oneshot channels, improving its usability in scenarios where the sender needs to know when there are no more receivers. Related: #2800

evanrittenhouse commented 3 months ago

I can pick this up