Trait OnDropFutureExt

Source
pub trait OnDropFutureExt
where Self: Future + Sized,
{ // Required method fn on_drop<D: FnMut()>(self, on_drop: D) -> OnDropFuture<Self, D> ; }
Expand description

Trait allowing you to attach a function to a Future that will be called when the future is dropped.

Required Methods§

Source

fn on_drop<D: FnMut()>(self, on_drop: D) -> OnDropFuture<Self, D>

Wraps the future with an OnDropFuture that will execute the given function when the future is dropped. This is useful for situations where some resources need to be cleaned up when the future goes away. Note; the function registered with this method will always run when the future is dropped which happens when a future is run to completion, and when it isn’t.

§Example
use twinkle_client::OnDropFutureExt;
use std::sync::{Mutex, Arc};
async move {
    let val1 = Arc::new(Mutex::new(0));
    let val2 = val1.clone();
    let val3 = val1.clone();
    let future = async {
        println!("In the future!");
        let mut val_lock = val1.lock().unwrap();
        assert_eq!(*val_lock, 0);
        *val_lock += 1;
    }.on_drop(move ||  {
        println!("On the drop");
        let mut val_lock = val2.lock().unwrap();
        assert_eq!(*val_lock, 1);
        *val_lock += 1;
    });
    future.await;
    assert_eq!(*val3.lock().unwrap(), 2);
};

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§