Open JanBeh opened 2 years ago
Apparently Sender
s without Receiver
s show some (maybe) surprising behavior:
use tokio::sync::watch;
#[allow(unused_variables)]
fn main() {
let (sender, receiver) = watch::channel("initial");
//drop(receiver); // try to uncomment
sender.send("updated").ok();
let receiver2 = sender.subscribe();
let s = *receiver2.borrow();
assert_eq!(s, "updated"); // fails if `receiver` is dropped before `send`
}
See also this post on URLO.
The other send methods (send_if_modified
, send_modify
, or send_replace
) don't exhibit this behavior, so the proposed feature is still useful.
I was also surprised by this, you can call broadcast::channel::<T>(CAPACITY).0
and send messages with the sender, they'll return an error, but you can just ignore them.
That's ok for broadcasts where you lose all messages previous to subscribing, implementing something else would be hard considering how it currently works.
Regarding watch
, I think that's odd, it should be possible to set a value before there are listeners and get it later with watch::Receiver::borrow
.
You can actually send a value without any receivers on a watch channel if you use send_modify
.
The send
method cannot be changed to allow this for backwards compatibility reasons.
Reopening since this also applies to the watch channel.
Is your feature request related to a problem?
I'm planning to create an SDR framework where data is streamed between certain "processing blocks". These blocks can be dynamically connected with each other (and disconnected). I planned to use
broadcast
"channels" for that purpose. However, when I create a producer, I might not have a consumer (yet), so I would only need abroadcast::Sender
. There is currently no way to create aSender
without also creating aReceiver
.A similar situation applies to
tokio::sync::watch
, where it's also not possible to create aSender
without aReceiver
.Describe the solution you'd like
I propose to add the following associated functions
tokio::sync::broadcast::Sender<T>::new(capacity: usize)
tokio::sync::watch::Sender<T>::new(init: T)
which act like
tokio::sync::broadcast::channel::<T>(capacity).0
tokio::sync::watch::channel::<T>(init).0
with the difference that the receiver isn't needlessly created and then dropped.
Describe alternatives you've considered
Using
.0
on the(Sender, Receiver)
pair is a good workaround, but might have unnecessary runtime overhead and is also less readable/verbose. Compare:vs
Additional context
Also note #4957.