Skip to main content

Deferred

Struct Deferred 

Source
pub struct Deferred<T> { /* private fields */ }
Available on crate feature alloc only.
Expand description

A background task whose result you can check or collect later.

Tasks run on any async runtime through a Spawner. With the default tokio feature, start and begin spawn on the current Tokio runtime.

The result is kept until you take it or drop the Deferred. Dropping a Deferred does not stop its task; use cancel for that.

§Examples

use async_deferred::Deferred;

let mut deferred = Deferred::start(async { 42 });

// ... do other work ...

assert_eq!(deferred.join().await, Ok(&42));

Implementations§

Source§

impl<T> Deferred<T>

Source

pub fn new() -> Self

Available on target_has_atomic=ptr only.

Creates a Deferred with no task. Start one with begin_on.

Source

pub fn start_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
where S: Spawner, F: Future<Output = T> + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr only.

Spawns future with spawner and returns its Deferred.

Returns an error if the runtime could not start the task, for example because its task pool is full. See Spawner for using your own runtime.

use async_deferred::Deferred;

// Start a task from outside a Tokio runtime
let runtime = tokio::runtime::Runtime::new().unwrap();
let mut deferred = Deferred::start_on(runtime.handle(), async { 42 }).unwrap();
assert_eq!(runtime.block_on(deferred.join()), Ok(&42));
Source

pub fn start_with_callback_on<S, F, C>( spawner: &S, future: F, callback: C, ) -> Result<Self, SpawnError>
where S: Spawner, F: Future<Output = T> + Send + 'static, C: FnOnce(&T) + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr only.

Like start_on, and runs callback with the result once future finishes.

The callback is not run if future panics, or if the task is cancelled or dropped by the runtime.

Source

pub fn begin_on<S, F>( &mut self, spawner: &S, future: F, ) -> Result<(), BeginError>
where S: Spawner, F: Future<Output = T> + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr only.

Spawns future with spawner.

Returns an error and does nothing if a task is running or its result has not been taken, or if the runtime could not start the task. A task that panicked or was dropped by the runtime does not prevent starting a new one.

Source

pub fn begin_with_callback_on<S, F, C>( &mut self, spawner: &S, future: F, callback: C, ) -> Result<(), BeginError>
where S: Spawner, F: Future<Output = T> + Send + 'static, C: FnOnce(&T) + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr only.

Like begin_on, and runs callback with the result once future finishes.

The callback is not run if future panics, or if the task is cancelled or dropped by the runtime.

Source

pub fn start_local_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
where S: LocalSpawner, F: Future<Output = T> + 'static, T: 'static,

Available on target_has_atomic=ptr only.

Like start_on, for futures that are not Send.

Source

pub fn start_with_callback_local_on<S, F, C>( spawner: &S, future: F, callback: C, ) -> Result<Self, SpawnError>
where S: LocalSpawner, F: Future<Output = T> + 'static, C: FnOnce(&T) + 'static, T: 'static,

Available on target_has_atomic=ptr only.

Like start_with_callback_on, for futures that are not Send.

Source

pub fn begin_local_on<S, F>( &mut self, spawner: &S, future: F, ) -> Result<(), BeginError>
where S: LocalSpawner, F: Future<Output = T> + 'static, T: 'static,

Available on target_has_atomic=ptr only.

Like begin_on, for futures that are not Send.

Source

pub fn begin_with_callback_local_on<S, F, C>( &mut self, spawner: &S, future: F, callback: C, ) -> Result<(), BeginError>
where S: LocalSpawner, F: Future<Output = T> + 'static, C: FnOnce(&T) + 'static, T: 'static,

Available on target_has_atomic=ptr only.

Like begin_with_callback_on, for futures that are not Send.

Source

pub async fn join(&mut self) -> Result<&T, Error>

Available on target_has_atomic=ptr only.

Waits for the task to finish and returns its result.

Returns immediately if the task already finished. If the task finished but its callback panicked, the result is still returned; check state to detect that.

use async_deferred::{Deferred, Error};

let mut deferred: Deferred<u32> = Deferred::start(async { panic!("boom") });
assert_eq!(deferred.join().await, Err(Error::Panicked("boom".into())));
Source

pub fn into_result(self) -> IntoResult<T> ⓘ

Available on target_has_atomic=ptr only.

Waits for the task to finish and returns its result, consuming the Deferred.

Same as .await on the Deferred. If the task finished but its callback panicked, the result is still returned. Dropping the returned future before it finishes does not stop the task.

use async_deferred::Deferred;

let deferred = Deferred::start(async { String::from("done") });
let value: String = deferred.into_result().await.unwrap();
assert_eq!(value, "done");

// `.await` on a `Deferred` does the same
let deferred = Deferred::start(async { 42 });
assert_eq!(deferred.await, Ok(42));
Source

pub fn state(&self) -> State

Available on target_has_atomic=ptr only.

Returns the current State without waiting.

The state is a snapshot: a task that has just finished may still show as State::Pending for an instant. Once it shows as finished, its result is available to try_get, take and join.

Source

pub fn panic_message(&mut self) -> Option<&str>

Available on target_has_atomic=ptr only.

Returns the panic message if the task or its callback panicked.

Catching a panic does not silence it: the panic hook still reports it, as for any other panic.

Source

pub fn try_get(&mut self) -> Option<&T>

Available on target_has_atomic=ptr only.

Returns the result if the task has finished, without waiting.

Source

pub fn take(&mut self) -> Option<T>

Available on target_has_atomic=ptr only.

Moves the result out if the task has finished, without waiting.

On success, the Deferred is reset and can start a new task.

use async_deferred::{Deferred, State};

let mut deferred = Deferred::start(async { vec![1, 2, 3] });
deferred.join().await.unwrap();
assert_eq!(deferred.take(), Some(vec![1, 2, 3]));
assert_eq!(deferred.state(), State::NotStarted);
Source

pub fn cancel(&mut self) -> bool

Available on target_has_atomic=ptr only.

Stops a running task and resets the Deferred so it can start a new one.

The task may still be using its runtime resources, such as an embassy task pool slot, when this returns. To start a new task right away in a full task pool, use cancel_and_wait instead. Returns false and does nothing if no task is running.

Cancelling is cooperative: the task stops at its next .await. Code that blocks without awaiting keeps running until it reaches one.

If the task finishes just as cancel runs, its result is discarded and cancel still returns true. To keep a result that has already arrived, call take first.

use async_deferred::{Deferred, State};

let mut deferred = Deferred::start(std::future::pending::<u32>());
assert!(deferred.cancel());
assert_eq!(deferred.state(), State::NotStarted);
Source

pub async fn cancel_and_wait(&mut self) -> bool

Available on target_has_atomic=ptr only.

Like cancel, and waits until the task has stopped.

On a single-threaded executor such as embassy, its task pool slot is free when this returns, so a new task can start right away even in a full pool. The task only stops while its runtime is running, so don’t await this from code that blocks the runtime. Returns false and does nothing if no task is running.

use async_deferred::{Deferred, State};

let mut deferred = Deferred::start(std::future::pending::<u32>());
assert!(deferred.cancel_and_wait().await);
assert_eq!(deferred.state(), State::NotStarted);
Source

pub fn is_ready(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the result is available, even if the callback panicked.

Source

pub fn is_complete(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the task and its callback finished without panicking.

Source

pub fn is_pending(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the task is still running.

Source

pub fn is_not_started(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if no task has been started, or its result was taken.

Source

pub fn has_task_panicked(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the task panicked.

Source

pub fn has_callback_panicked(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the task finished but its callback panicked.

Source

pub fn is_cancelled(&self) -> bool

Available on target_has_atomic=ptr only.

Returns true if the runtime dropped the task before it finished.

A task stopped with cancel is not reported here: cancelling resets the Deferred to State::NotStarted.

Source§

impl<T> Deferred<T>

Source

pub fn start<F>(future: F) -> Self
where F: Future<Output = T> + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr and crate feature tokio only.

Spawns future on the current Tokio runtime and returns its Deferred.

§Panics

Panics if called outside a Tokio runtime. Use start_on with a tokio::runtime::Handle there.

Source

pub fn start_with_callback<F, C>(future: F, callback: C) -> Self
where F: Future<Output = T> + Send + 'static, C: FnOnce(&T) + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr and crate feature tokio only.

Like start, and runs callback with the result once future finishes.

The callback is not run if future panics, or if the task is cancelled or dropped by the runtime.

§Panics

Panics if called outside a Tokio runtime. Use start_with_callback_on with a tokio::runtime::Handle there.

use async_deferred::Deferred;

let deferred = Deferred::start_with_callback(
    async { 42 },
    |result| println!("computed {result}"),
);
Source

pub fn begin<F>(&mut self, future: F) -> Result<(), BeginError>
where F: Future<Output = T> + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr and crate feature tokio only.

Spawns future on the current Tokio runtime.

Returns BeginError::AlreadyStarted and does nothing if a task is running or its result has not been taken. A task that panicked or was dropped by the runtime does not prevent starting a new one.

Outside a Tokio runtime, returns BeginError::Spawn.

use async_deferred::Deferred;

let mut deferred = Deferred::new();
assert!(deferred.begin(async { 42 }).is_ok());
assert!(deferred.begin(async { 24 }).is_err());
Source

pub fn begin_with_callback<F, C>( &mut self, future: F, callback: C, ) -> Result<(), BeginError>
where F: Future<Output = T> + Send + 'static, C: FnOnce(&T) + Send + 'static, T: Send + 'static,

Available on target_has_atomic=ptr and crate feature tokio only.

Like begin, and runs callback with the result once future finishes.

The callback is not run if future panics, or if the task is cancelled or dropped by the runtime.

Trait Implementations§

Source§

impl<T: Debug> Debug for Deferred<T>

Available on target_has_atomic=ptr only.
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Default for Deferred<T>

Available on target_has_atomic=ptr only.
Source§

fn default() -> Self

Same as Deferred::new.

Source§

impl<T> IntoFuture for Deferred<T>

Available on target_has_atomic=ptr only.
Source§

fn into_future(self) -> IntoResult<T> ⓘ

Source§

type Output = Result<T, Error>

The output that the future will produce on completion.
Source§

type IntoFuture = IntoResult<T>

Which kind of future are we turning this into?

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Deferred<T>

§

impl<T> !UnwindSafe for Deferred<T>

§

impl<T> Forget for Deferred<T>

§

impl<T> Freeze for Deferred<T>
where Inner<T>: Freeze,

§

impl<T> Move for Deferred<T>

§

impl<T> Send for Deferred<T>
where Inner<T>: Send,

§

impl<T> Sync for Deferred<T>
where Inner<T>: Sync,

§

impl<T> Unpin for Deferred<T>
where Inner<T>: Unpin,

§

impl<T> UnsafeUnpin for Deferred<T>
where Inner<T>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.