maycoon_core/tasks/
mod.rs

1use crate::tasks::runner::TaskRunner;
2use std::future::Future;
3use std::sync::OnceLock;
4
5pub use futures::future;
6
7/// Contains the [`runner::TaskRunner`] struct.
8pub mod runner;
9
10/// A handle to a running task which can be awaited in order to get its result.
11pub type TaskHandle<T> = future::RemoteHandle<T>;
12
13static RUNNER: OnceLock<TaskRunner> = OnceLock::new();
14
15/// Returns the global [`TaskRunner`] or [`None`] if it hasn't been initialized yet.
16pub fn runner<'a>() -> Option<&'a TaskRunner> {
17    RUNNER.get()
18}
19
20/// Spawns the given [`Future`] on the task runner thread pool and returns a [`TaskHandle`] to await for the result.
21///
22/// Panics if the task runner hasn't been initialized yet.
23pub fn spawn<Fut>(fut: Fut) -> TaskHandle<Fut::Output>
24where
25    Fut: Future + Send + 'static,
26    Fut::Output: Send,
27{
28    runner().expect("Task runner not initialized yet").run(fut)
29}
30
31/// Blocks on the given [`Future`] on the task runner thread pool and returns the output.
32pub fn block_on<Fut>(fut: Fut) -> Fut::Output
33where
34    Fut: Future,
35{
36    futures::executor::block_on(fut)
37}