Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Created July 24, 2014 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendanzab/64b22f322c6d2ca9fa32 to your computer and use it in GitHub Desktop.
Save brendanzab/64b22f322c6d2ca9fa32 to your computer and use it in GitHub Desktop.
/// Sends cloned values to multiple monitoring `Receiver`s.
pub struct Signal<T> {
txs: Vec<Sender<T>>,
}
impl<T: Send> Signal<T> {
/// Create a signal with no monitors connected.
pub fn new() -> Signal<T> {
Signal { txs: Vec::new() }
}
/// Create a new `Receiver` to monitor signals.
pub fn new_monitor(&mut self) -> Receiver<T> {
let (tx, rx) = channel();
self.txs.push(tx);
rx
}
}
impl<T: Clone + Send> Signal<T> {
/// Sends a clone of signal `x` to each connected `Receiver`.
pub fn send(&mut self, x: T) {
let txs = mem::replace(&mut self.txs, Vec::new());
// orphaned `Sender`s will be removed from `txs`
self.txs = txs.move_iter().filter(|tx| {
tx.send_opt(x.clone()).is_ok()
}).collect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment