I have an async function which I want to run in the background. This function is part of a call hierarchy which is not using async calls.
My call hierarchy looks like this:
struct Handler {}
impl Handler {
pub async fn handle(&self) {
/// does some stuff and updates internal caches
}
}
struct Client_v2 {
handler: Handler,
rt: tokio::runtime::Runtime,
}
impl Client_v2 {
fn do_work(&self) {
let future = self.handler(handle);
self.rt.spawn(future); // want this to run in background and not block!
// `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
}
}
From what I understand there is some issue where perhaps the client could outlive its owner Client_v2
leading to this error.
How should I go about making this lifetime valid? do I need to resort to creating threads and moving objects in and out of the thread scope? This function is called very frequently.
Alternatively to @sebpuetz problem explanation. In rust you can wrap your type in
Arc
to being able to share its state, so you can move it (a clone of the Arc) to the future you need to compute:Playground