Skip to content

Is there any way to perform a POST request on drop? #3815

Answered by davidpdrsn
stevepryde asked this question in Q&A
Discussion options

You must be logged in to vote

Async drop isn't directly supported at the moment unfortunately.

One workaround I've used in the past is spawning a task that receives on a oneshot channel, which MyStruct sends to in its destructor. Something like:

use tokio::sync::oneshot;

async fn some_function() {
    let (tx, mut rx) = oneshot::channel();

    let my_struct = MyStruct { tx: Some(tx) };

    tokio::spawn(async move {
        let msg = rx.await;
        // `my_struct` was dropped
    });
}

struct Msg;

struct MyStruct {
    tx: Option<oneshot::Sender<Msg>>,
}

impl Drop for MyStruct {
    fn drop(&mut self) {
        self.tx.take().expect("dropped twice").send(Msg);
    }
}

The task could be seen as a kind of "actor".

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
5 replies
@stevepryde
Comment options

@Darksonn
Comment options

@stevepryde
Comment options

@Darksonn
Comment options

@stevepryde
Comment options

Answer selected by stevepryde
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants