diff --git a/src/reactor/mod.rs b/src/reactor/mod.rs index 39c490a8..72dd4a8f 100644 --- a/src/reactor/mod.rs +++ b/src/reactor/mod.rs @@ -254,6 +254,13 @@ impl Core { self.poll(max_wait); } + /// Run the event loop until all spawned futures complete. + pub fn run_until_finished(&mut self) { + while self.inner.borrow().live() { + self.turn(None); + } + } + fn poll(&mut self, max_wait: Option) -> bool { // Given the `max_wait` variable specified, figure out the actual // timeout that we're going to pass to `poll`. This involves taking a @@ -570,6 +577,11 @@ impl Inner { _registration: pair.0, }); } + + /// Deterimne whether the core has work scheduled + fn live(&self) -> bool { + !self.io_dispatch.is_empty() || !self.task_dispatch.is_empty() || !self.timeouts.is_empty() + } } impl Remote { diff --git a/tests/spawn.rs b/tests/spawn.rs index 98434a81..5fafca5e 100644 --- a/tests/spawn.rs +++ b/tests/spawn.rs @@ -6,6 +6,8 @@ use std::any::Any; use std::sync::mpsc; use std::thread; use std::time::Duration; +use std::rc::Rc; +use std::cell::Cell; use futures::{Future, Poll}; use futures::future; @@ -145,3 +147,16 @@ fn spawn_in_drop() { lp.run(rx).unwrap(); } + +#[test] +fn run_until_finished() { + drop(env_logger::init()); + let mut lp = Core::new().unwrap(); + let ran = Rc::new(Cell::new(false)); + { + let ran = ran.clone(); + lp.handle().spawn(future::lazy(move || { ran.set(true); Ok(()) })); + } + lp.run_until_finished(); + assert!(ran.get()); +}