Skip to main content

datex_core/utils/
async_callback.rs

1use futures::future::LocalBoxFuture;
2
3use crate::prelude::*;
4
5/// A generic async callback wrapper.
6/// Can be cloned and called from multiple tasks.
7pub struct AsyncCallback<In, Out> {
8    inner: Rc<dyn Fn(In) -> LocalBoxFuture<'static, Out>>,
9}
10
11impl<In, Out> Clone for AsyncCallback<In, Out> {
12    fn clone(&self) -> Self {
13        Self {
14            inner: self.inner.clone(),
15        }
16    }
17}
18
19impl<In, Out> AsyncCallback<In, Out> {
20    /// Create a new AsyncCallback from an async function or closure.
21    pub fn new<F, Fut>(f: F) -> Self
22    where
23        F: Fn(In) -> Fut + 'static,
24        Fut: core::future::Future<Output = Out> + 'static,
25    {
26        Self {
27            inner: Rc::new(move |arg| Box::pin(f(arg))),
28        }
29    }
30
31    /// Call the async callback.
32    pub async fn call(&self, arg: In) -> Out {
33        (self.inner)(arg).await
34    }
35}