pub struct Broadcast<T> { /* private fields */ }Expand description
An object that received data from a provided Receiver, and broadcasts the data to all
subscribers.
Using a Broadcast yields the following benefits:
- Send received data to multiple endpoint. A
Broadcastobject can be used to build a web of objects.
§Example
#![feature(coroutines, coroutine_trait, stmt_expr_attributes)]
#![feature(unboxed_closures)]
use reflux::{Inlet, Outlet, Broadcast};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crossbeam_channel::Receiver;
use reflux::add_routine;
use crossbeam_channel::unbounded;
use std::time::Duration;
use std::thread::sleep;
let stop_flag = Arc::new(AtomicBool::new(false));
let test_inlet: (Inlet, Receiver<String>) = Inlet::new(add_routine!(#[coroutine] || {
sleep(Duration::from_secs(1));
yield "hello".to_string()
}), stop_flag.clone(), ());
let (test_outlet1_sink, test_outlet1_source) = unbounded();
let (test_outlet2_sink, test_outlet2_source) = unbounded();
let (test_outlet1, test1_tx) = Outlet::new(move |example: String| {
test_outlet1_sink.send(format!("1: {example}")).unwrap()
}, stop_flag.clone());
let (test_outlet2, test2_tx) = Outlet::new(move |example: String| {
test_outlet2_sink.send(format!("2: {example}")).unwrap()
}, stop_flag.clone());
let mut broadcaster = Broadcast::new(test_inlet.1, stop_flag.clone());
broadcaster.subscribe(test1_tx);
broadcaster.subscribe(test2_tx);
let data1 = test_outlet1_source.recv().unwrap();
let data2 = test_outlet2_source.recv().unwrap();
stop_flag.store(true, Ordering::Relaxed);
test_outlet1.join().unwrap();
test_outlet2.join().unwrap();
test_inlet.0.join().unwrap();
broadcaster.join().unwrap();
assert_eq!(data1, "1: hello".to_string());
assert_eq!(data2, "2: hello".to_string());Implementations§
source§impl<T> Broadcast<T>
impl<T> Broadcast<T>
sourcepub fn new(source: Receiver<T>, stop_sig: Arc<AtomicBool>) -> Self
pub fn new(source: Receiver<T>, stop_sig: Arc<AtomicBool>) -> Self
sourcepub fn channel(&mut self) -> Receiver<T>
pub fn channel(&mut self) -> Receiver<T>
Create a subscription for an external object to use to receive data from the Broadcast.
Note: Subscription is based on an unbounded channel.
§Returns
- A
Receiverobject from which to receive data.
Auto Trait Implementations§
impl<T> Freeze for Broadcast<T>
impl<T> !RefUnwindSafe for Broadcast<T>
impl<T> Send for Broadcast<T>where
T: Send,
impl<T> Sync for Broadcast<T>where
T: Send,
impl<T> Unpin for Broadcast<T>
impl<T> !UnwindSafe for Broadcast<T>
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more