bevy_tasks/task.rs
1use core::{
2 future::Future,
3 pin::Pin,
4 task::{Context, Poll},
5};
6
7/// Wraps `async_executor::Task`, a spawned future.
8///
9/// Tasks are also futures themselves and yield the output of the spawned future.
10///
11/// When a task is dropped, its gets canceled and won't be polled again. To cancel a task a bit
12/// more gracefully and wait until it stops running, use the [`Task::cancel()`] method.
13///
14/// Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic.
15#[derive(Debug)]
16#[must_use = "Tasks are canceled when dropped, use `.detach()` to run them in the background."]
17pub struct Task<T>(async_executor::Task<T>);
18
19impl<T> Task<T> {
20 /// Creates a new task from a given `async_executor::Task`
21 pub fn new(task: async_executor::Task<T>) -> Self {
22 Self(task)
23 }
24
25 /// Detaches the task to let it keep running in the background. See
26 /// `async_executor::Task::detach`
27 pub fn detach(self) {
28 self.0.detach();
29 }
30
31 /// Cancels the task and waits for it to stop running.
32 ///
33 /// Returns the task's output if it was completed just before it got canceled, or [`None`] if
34 /// it didn't complete.
35 ///
36 /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of
37 /// canceling because it also waits for the task to stop running.
38 ///
39 /// See `async_executor::Task::cancel`
40 pub async fn cancel(self) -> Option<T> {
41 self.0.cancel().await
42 }
43
44 /// Returns `true` if the current task is finished.
45 ///
46 ///
47 /// Unlike poll, it doesn't resolve the final value, it just checks if the task has finished.
48 /// Note that in a multithreaded environment, this task can be finished immediately after calling this function.
49 pub fn is_finished(&self) -> bool {
50 self.0.is_finished()
51 }
52}
53
54impl<T> Future for Task<T> {
55 type Output = T;
56
57 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58 Pin::new(&mut self.0).poll(cx)
59 }
60}