A strategy for using the [event-listener
] crate in both blocking and non-blocking contexts.
One of the stand-out features of the [event-listener
] crate is the ability to use it in both
asynchronous and synchronous contexts. However, sometimes using it like this causes a lot of
boilerplate to be duplicated. This crate aims to reduce that boilerplate by providing an EventListenerFuture
trait that implements both blocking and non-blocking functionality.
``` use eventlistener::{Event, EventListener}; use eventlistener_strategy::{EventListenerFuture, FutureWrapper, Strategy};
use std::pin::Pin; use std::task::Poll; use std::thread; use std::sync::Arc;
// A future that waits three seconds for an event to be fired. fn waitthreeseconds() -> WaitThreeSeconds { let event = Event::new(); let listener = event.listen();
thread::spawn(move || {
thread::sleep(std::time::Duration::from_secs(3));
event.notify(1);
});
WaitThreeSeconds { listener }
}
struct WaitThreeSeconds {
listener: Pin
impl EventListenerFuture for WaitThreeSeconds { type Output = ();
fn poll_with_strategy<'a, S: Strategy<'a>>(
mut self: Pin<&'a mut Self>,
strategy: &mut S,
context: &mut S::Context,
) -> Poll<Self::Output> {
strategy.poll(self.listener.as_mut(), context)
}
}
// Use the future in a blocking context. let future = waitthreeseconds(); future.wait();
// Use the future in a non-blocking context. futureslite::future::blockon(async { let future = FutureWrapper::new(waitthreeseconds()); future.await; }); ```
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.