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.
7#[derive(Clone)]
8pub struct AsyncCallback<In, Out> {
9    inner: Rc<dyn Fn(In) -> LocalBoxFuture<'static, Out>>,
10}
11
12impl<In, Out> AsyncCallback<In, Out> {
13    /// Create a new AsyncCallback from an async function or closure.
14    pub fn new<F, Fut>(f: F) -> Self
15    where
16        F: Fn(In) -> Fut + 'static,
17        Fut: core::future::Future<Output = Out> + 'static,
18    {
19        Self {
20            inner: Rc::new(move |arg| Box::pin(f(arg))),
21        }
22    }
23
24    /// Call the async callback.
25    pub async fn call(&self, arg: In) -> Out {
26        (self.inner)(arg).await
27    }
28}