I have a resource ResMut<ClientConnection> and I would like to start an async task on it, like so:
fn connect(mut netclient: ResMut<ClientConnection>,) {
info!("calling connect on netclient");
let task_handle = IoTaskPool::get().spawn(Compat::new(async { netclient.connect().await }));
// do other stuff with the task handle
}
The issue is that I can't pass the &mut Res into the task; I get an error like
407 | fn connect(mut netclient: ResMut<ClientConnection>, mut state: ResMut<ConnectingState>) {
| -------------
| |
| `netclient` is a reference that is only valid in the function body
| has type `bevy::prelude::ResMut<'1, connection::client::ClientConnection>`
408 | info!("calling connect on netclient");
409 | let connection_task = IoTaskPool::get().spawn(Compat::new(async { netclient.connect().await }));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `netclient` escapes the function body here
| argument requires that `'1` must outlive `'static`
|
= note: requirement occurs because of a mutable reference to `bevy::prelude::ResMut<'_, connection::client::ClientConnection>`
= note: mutable references are invariant over their type parameter
= help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance
I can't use async move either because I don't own the resource.
I guess a solution would be to remove the resource from the world so that I own it, launch the task, and then maybe re-add the resource to the world after the task ends, but that isn't very ergonomic.
Is there a good way to do this?