pub struct BroadcastChannel<T>where
T: Clone,{ /* private fields */ }
Expand description
A channel that broadcasts values to attached senders.
This is part of the BroadcastResponse
message behavior to efficiently send delayed responses
to a large number of senders. All requests that are attached to this channel via their senders
resolve with the same value.
§Example
use relay_system::{BroadcastChannel, BroadcastSender};
struct MyService {
channel: Option<BroadcastChannel<String>>,
}
impl MyService {
fn handle_message(&mut self, sender: BroadcastSender<String>) {
if let Some(ref mut channel) = self.channel {
channel.attach(sender);
} else {
self.channel = Some(sender.into_channel());
}
}
fn finish_compute(&mut self, value: String) {
if let Some(channel) = self.channel.take() {
channel.send(value);
}
}
}
Implementations§
source§impl<T: Clone> BroadcastChannel<T>
impl<T: Clone> BroadcastChannel<T>
sourcepub fn new() -> Self
pub fn new() -> Self
Creates a standalone channel.
Use attach
to add senders to this channel. Alternatively, create a channel
with BroadcastSender::into_channel
.
sourcepub fn attach(&mut self, sender: BroadcastSender<T>)
pub fn attach(&mut self, sender: BroadcastSender<T>)
Attaches a sender of another message to this channel to receive the same value.
§Example
use relay_system::{BroadcastChannel, BroadcastResponse, BroadcastSender};
// This is usually done as part of `Addr::send`
let (sender, rx) = BroadcastResponse::<&str>::channel();
let mut channel = BroadcastChannel::new();
channel.attach(sender);
sourcepub fn send(self, value: T)
pub fn send(self, value: T)
Sends a value to all attached senders and closes the channel.
This method succeeds even if no senders are attached to this channel anymore. To check if
this channel is still active with senders attached, use is_attached
.
§Example
use relay_system::BroadcastResponse;
// This is usually done as part of `Addr::send`
let (sender, rx) = BroadcastResponse::<&str>::channel();
let channel = sender.into_channel();
channel.send("test");
assert_eq!(rx.await, Ok("test"));
sourcepub fn is_attached(&self) -> bool
pub fn is_attached(&self) -> bool
Returns true
if there are requests waiting for this channel.
The channel is not permanently closed when all waiting requests have detached. A new sender
can be attached using attach
even after this method returns false
.
§Example
use relay_system::BroadcastResponse;
// This is usually done as part of `Addr::send`
let (sender, rx) = BroadcastResponse::<&str>::channel();
let channel = sender.into_channel();
assert!(channel.is_attached());
drop(rx);
assert!(!channel.is_attached());