DEV Community

Discussion on: Rust futures: an uneducated, short and hopefully not boring tutorial - Part 5 - Streams

Collapse
 
patrikstas profile image
Patrik Staš

Hi Francesco, thanks for this series. However in this part5, I found that you didn't describe changes required last to run() examples to work (maybe intentionally as exercise?)

Anyway, if anyone is struggling, here's a cheat sheet _.

Add core_handle to MyStream

impl MyStream {
    pub fn new(max: u32, core_handle: tokio_core::reactor::Handle) -> MyStream {
        MyStream {
            current: 0,
            max,
            core_handle
        }
    }
}

Add thread_name to WaitInAnotherThread Future

pub struct WaitInAnotherThread {
    end_time: DateTime<Utc>,
    running: bool,
    thread_name: String
}

and extend its constructor

impl WaitInAnotherThread {
    pub fn new(delay_seconds: i64, thread_name: String) -> WaitInAnotherThread {
        WaitInAnotherThread {
            end_time:  Utc::now() +  chrono::Duration::seconds(delay_seconds),
            running: false,
            thread_name: thread_name
        }
    }

WaitForAnotherThread Future must have Error type (). Also add thread_name to print outs.

impl Future for WaitInAnotherThread {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if Utc::now() < self.end_time {
            println!("{} :: not ready yet! parking the task.", self.thread_name);

            if !self.running {
                println!("{} :: side thread not running! starting now!", self.thread_name);
                self.run(task::current());
                self.running = true;
            }

            Ok(Async::NotReady)
        } else {
            println!("{} :: ready! the task will complete.", self.thread_name);
            Ok(Async::Ready(()))
        }
    }
}