Skip to main content

ankurah_core/
task.rs

1use std::future::Future;
2
3#[cfg(not(target_arch = "wasm32"))]
4static RUNTIME_HANDLE: std::sync::OnceLock<tokio::runtime::Handle> = std::sync::OnceLock::new();
5
6/// Inject a Tokio runtime handle for use by ankurah.
7///
8/// The handle is used as a fallback when `spawn` is called from threads
9/// without a Tokio runtime context (e.g. GC/finalizer threads in FFI).
10#[cfg(not(target_arch = "wasm32"))]
11pub fn set_runtime_handle(handle: tokio::runtime::Handle) { RUNTIME_HANDLE.set(handle).ok(); }
12
13/// Spawn a task.
14///
15/// On native, tries the thread-local runtime context first, then falls back
16/// to the handle provided via [`set_runtime_handle`].
17#[cfg(not(target_arch = "wasm32"))]
18pub fn spawn<F>(future: F)
19where
20    F: Future + Send + 'static,
21    <F as futures::Future>::Output: std::marker::Send,
22{
23    match tokio::runtime::Handle::try_current() {
24        Ok(handle) => {
25            handle.spawn(future);
26        }
27        Err(_) => {
28            RUNTIME_HANDLE
29                .get()
30                .expect("task::spawn: no Tokio runtime context on this thread. Call ankurah::set_runtime_handle() at init time.")
31                .spawn(future);
32        }
33    }
34}
35
36#[cfg(target_arch = "wasm32")]
37pub fn spawn<F>(future: F)
38where F: Future<Output = ()> + Send + 'static {
39    wasm_bindgen_futures::spawn_local(future);
40}