Question: what is the proper way to poll events?
Created by: little-dude
Hi,
I'd like to read events in a non-blocking way, which is not possible with termion::input::Events
since calling next()
blocks. I tried the following:
pub struct Input {
tx: mpsc::Sender<termion::event::Event>,
rx: mpsc::Receiver<termion::event::Event>,
}
impl Input {
pub fn new() -> Input {
let (tx, rx) = mpsc::channel();
Input {
tx: tx,
rx: rx,
}
}
pub fn run(&mut self) {
let tx = self.tx.clone();
thread::spawn(move || {
let events = input::Events {
// does not compile!
bytes: async_stdin().bytes()
};
loop {
match events.next() {
Some(result) => {
match result {
Ok(event) => {
tx.send(event);
},
Err(err) => {
error!("{:?}", err);
},
}
},
None => {},
}
}
});
}
}
Then I could do something like this:
let mut input = Input::new();
input.run();
loop {
match input.rx.try_recv() {
Ok(event) => {
match event {
// TODO: handle the event
_ => {}
}
}
Err(_) => {
// Just wait a little bit before continuing so that we don't eat too much cpu
thread::sleep_ms(10);
}
}
// Do other stuff here
// [...]
}
However my code does not compile:
error[E0451]: field `bytes` of struct `termion::input::Events` is private
--> src/main.rs:66:17
|
66 | bytes: async_stdin().bytes()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ field `bytes` is private
I assume this field is private for a good reason, and I'm doing things the wrong way. What would be the "right" way to poll events? Sorry if the code is not very good, I'm still struggling with rust basics.