vexide_async/
task.rs

1//! Asynchronous tasks.
2
3use std::{future::Future, rc::Rc};
4
5pub use crate::local::{task_local, LocalKey};
6use crate::{executor::EXECUTOR, local::TaskLocalStorage};
7
8// public because it's used in Task<T> and InfallibleTask<T>
9#[doc(hidden)]
10#[derive(Debug)]
11pub struct TaskMetadata {
12    pub(crate) tls: Rc<TaskLocalStorage>,
13}
14
15/// A spawned task.
16///
17/// A [`Task`] can be awaited to retrieve the output of its future.
18///
19/// Dropping a [`Task`] cancels it, which means its future won't be polled again. To drop the
20/// [`Task`] handle without canceling it, use [`detach()`][`Task::detach()`] instead. To cancel a
21/// task gracefully and wait until it is fully destroyed, use the [`cancel()`][Task::cancel()]
22/// method.
23///
24/// # Examples
25///
26/// ```
27/// use vexide::async_runtime::spawn;
28///
29/// // Spawn a future onto the executor.
30/// let task = spawn(async {
31///     println!("Hello from a task!");
32///     1 + 2
33/// });
34///
35/// // Wait for the task's output.
36/// assert_eq!(task.await, 3);
37/// ```
38pub type Task<T> = async_task::Task<T, TaskMetadata>;
39
40/// A spawned task with a fallible response.
41pub type FallibleTask<T> = async_task::FallibleTask<T, TaskMetadata>;
42
43/// Spawns a new async task that can be controlled with the returned task handle.
44pub fn spawn<T>(future: impl Future<Output = T> + 'static) -> Task<T> {
45    EXECUTOR.with(|ex| ex.spawn(future))
46}