re_viewer_context/
async_runtime_handle.rs

1#[cfg(not(target_arch = "wasm32"))]
2pub trait WasmNotSend: Send {}
3
4#[cfg(target_arch = "wasm32")]
5pub trait WasmNotSend {}
6
7#[cfg(not(target_arch = "wasm32"))]
8impl<T: Send> WasmNotSend for T {}
9
10#[cfg(target_arch = "wasm32")]
11impl<T> WasmNotSend for T {}
12
13#[derive(Debug, thiserror::Error)]
14pub enum AsyncRuntimeError {
15    /// Tokio returned an error.
16    ///
17    /// We cannot leak a tokio type, so we have to convert it to a string.
18    #[error("Tokio error: {0}")]
19    TokioError(String),
20}
21
22/// Thin abstraction over the async runtime.
23///
24/// This allows us to use tokio on native and the browser futures.
25#[derive(Clone)]
26pub struct AsyncRuntimeHandle {
27    #[cfg(not(target_arch = "wasm32"))]
28    tokio: tokio::runtime::Handle,
29}
30
31impl AsyncRuntimeHandle {
32    #[cfg(not(target_arch = "wasm32"))]
33    pub fn new_native(tokio: tokio::runtime::Handle) -> Self {
34        Self { tokio }
35    }
36
37    #[cfg(target_arch = "wasm32")]
38    pub fn new_web() -> Self {
39        Self {}
40    }
41
42    #[cfg(not(target_arch = "wasm32"))]
43    pub fn inner(&self) -> &tokio::runtime::Handle {
44        &self.tokio
45    }
46
47    /// Create an `AsyncRuntime` from the current tokio runtime on native.
48    #[cfg_attr(target_arch = "wasm32", expect(clippy::unnecessary_wraps))]
49    pub fn from_current_tokio_runtime_or_wasmbindgen() -> Result<Self, AsyncRuntimeError> {
50        #[cfg(target_arch = "wasm32")]
51        {
52            Ok(Self::new_web())
53        }
54        #[cfg(not(target_arch = "wasm32"))]
55        {
56            Ok(Self::new_native(
57                tokio::runtime::Handle::try_current()
58                    .map_err(|err| AsyncRuntimeError::TokioError(err.to_string()))?
59                    .clone(),
60            ))
61        }
62    }
63
64    #[cfg(target_arch = "wasm32")]
65    #[expect(clippy::unused_self)]
66    pub fn spawn_future<F>(&self, future: F)
67    where
68        F: std::future::Future<Output = ()> + WasmNotSend + 'static,
69    {
70        wasm_bindgen_futures::spawn_local(future);
71    }
72
73    #[cfg(not(target_arch = "wasm32"))]
74    pub fn spawn_future<F>(&self, future: F)
75    where
76        F: std::future::Future<Output = ()> + WasmNotSend + 'static,
77    {
78        self.tokio.spawn(future);
79    }
80}