graphrefly/
async_driver.rs1use std::future::Future;
8use std::pin::Pin;
9use std::rc::Rc;
10use std::time::Duration;
11
12pub type DriverCancel = Box<dyn FnOnce()>;
15
16pub trait LocalAsyncDriver {
20 fn sleep(&self, duration: Duration, callback: Box<dyn FnOnce()>) -> DriverCancel;
22 fn interval(&self, period: Duration, callback: Rc<dyn Fn()>) -> DriverCancel;
24 fn spawn_local(&self, fut: Pin<Box<dyn Future<Output = ()> + 'static>>) -> DriverCancel;
26}
27
28#[cfg(feature = "tokio")]
29#[derive(Debug, Clone, Copy, Default)]
30pub struct TokioLocalDriver;
32
33#[cfg(feature = "tokio")]
34impl LocalAsyncDriver for TokioLocalDriver {
35 fn sleep(&self, duration: Duration, callback: Box<dyn FnOnce()>) -> DriverCancel {
36 let handle = tokio::task::spawn_local(async move {
37 tokio::time::sleep(duration).await;
38 callback();
39 });
40 Box::new(move || handle.abort())
41 }
42
43 fn interval(&self, period: Duration, callback: Rc<dyn Fn()>) -> DriverCancel {
44 let handle = tokio::task::spawn_local(async move {
45 loop {
46 tokio::time::sleep(period).await;
47 callback();
48 }
49 });
50 Box::new(move || handle.abort())
51 }
52
53 fn spawn_local(&self, fut: Pin<Box<dyn Future<Output = ()> + 'static>>) -> DriverCancel {
54 let handle = tokio::task::spawn_local(fut);
55 Box::new(move || handle.abort())
56 }
57}