How to mutate state with a value produced by an async method?

i am building a client application that performs some networking against a server. i'm at the beginning of building it, so all i want to do at the moment is fetch results and display them. i am trying to do so with async/await to learn asynchronous rust.

the problem i'm running into is that spawn/spawn_local require Future that has 'static lifetime. however, i want to update state on self. i guess one way to do this is to use a channel and send messages back to the main thread that owns self. however, i'd like to learn how i would do this using the correct rust primitives. i have tried to use Mutex<Rc<Cell<T>>> but i still get the same lifetime error.

how can i get the async block to have a reference that lives beyond the scope of the function? i tried async move but that doesn't seem to do what i want either.

i have written this playground that demonstrates my issue:

note: i guess i don't need Mutex since i'm using LocalSpawnExt and spawn_local, but, even if i remove Mutex, i get the same error.

perhaps i have solved my own problem:

  • since i'm using spawn_local, i am doing everything on a single thread and don't need to worry about an executor taking things to another thread. therefore, i can remove Mutex.
  • i can then use Rc::clone to clone the reference to the underlying Cell, which i can then set in the async move block. i changed the playground this way:

(i unfortunately didn't realize that would change the playground pointed to by the permalink, so i don't think the buggy version is available anymore)

You need to hit share again to generate a new link. The playground links are immutable, so your link still points to the original.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.