14. MAKING IT CURRENT
Meet Arc<Mutex<T>>>
usestd::io::BufRead;
usestd::io::BufStream;
usestd::net::TcpStream;
usestd::sync::{Arc,Mutex};
fnmain(){
letstream =TcpStream::connect("demo.nats.io:4222").unwrap();
letmutnats_io=BufStream::new(stream);
letmutio=Arc::new(Mutex::new(nats_io));
//Andeachtimewewanttouseit
letmutcloned_nats_io=self.io.clone();
letmutborrowed_io=cloned_nats_io.try_lock().unwrap();
letmutline=String::new();
letresult=borrowed_io.read_line(&mutline);
println!("Gotthis:{}",line);
}
15. CALLBACKS
(This was the hardest part…)
How to dispatch the subscription callbacks?
usestd::collections::HashMap;
usestd::sync::{Arc,Mutex};
usestd::thread;
pubstructCallbackStore{
cid:u8,
cbs:Arc<Mutex<HashMap<u8,Box<Fn(&str)+Send>>>>
}
18. DISPATCH!
Store callbacks by putting them in a Box:
fnmain(){
println!("Storingsomecallbacks...");
letmutstore=CallbackStore::new();
store.add_callback(Box::new(|msg|{
println!("Yougotit!Thisisit:{}",msg);
}));
store.add_callback(Box::new(|msg|{
println!("Andthisis:{}",msg);
}));
dispatcher_loop(store.cbs.clone());
thread::sleep_ms(1000);
}