Search code examples
rustchannelrust-tokio

What is the difference between cloning the receiver and subscribing to the sender in a tokio watch channel?


When using a tokio watch channel I noticed I can use the subscribe method in the sender to get another receiver or I can clone the existing receiver:

let (sender, mut receiver) = watch::channel(1);

let receiver_2 = sender.subscribe();
let receiver_3 = receiver.clone();

both receiver_2 and receiver_3 seem to work the same but is there an major difference that I'm missing?


Solution

  • Looking at the source code for Receiver::clone and Sender::subscribe, there is no difference in the created receiver: they both amount to Receiver::from_shared (sender.shared.state.load().version(), sender.shared.clone()).

    The only difference is that Sender::subscribe will reopen the sender if there were no existing receivers.