Is there any way to perform a POST request on drop? #3815
-
I have a library ( However when I try to perform a request on drop it deadlocks when using the single-threaded tokio executor. Things I've tried so far:
Is there any possible way to make a POST request on drop, with reqwest, running under tokio's basic scheduler? Simple example: pub struct MyStruct {}
impl Drop for MyStruct {
fn drop(&mut self) {
// is there any way to make an async request here using reqwest?
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
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 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". |
Beta Was this translation helpful? Give feedback.
-
The Rust language does not support asynchronous code in destructors. Tokio's The simplest option is probably to just spawn a task: pub struct MyStruct {}
impl Drop for MyStruct {
fn drop(&mut self) {
tokio::spawn(async move {
// async code can go here
});
}
} |
Beta Was this translation helpful? Give feedback.
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:The task could be seen as a kind of "actor".