#How to update State from detached thread?

1 messages · Page 1 of 1 (latest)

broken owl
#

I would like to learn how to update a managed state once its been passed into a thread.

So far I have

... 
tauri::Builder::default()
        .setup(|app| {
            app.manage(LockedAppState(Default::default()));
            let handle = app.handle().clone();
            tauri::async_runtime::spawn( async move  {
                discovery(handle).await;
            });
            Ok(())
        })
... ```

then in the udp discovery thread
```Rust
...
pub async fn discovery(app_handle: AppHandle) {
        //== Create the mDNS daemon
        //== Browse for "_osc._udp.local." services
        let mdns = ServiceDaemon::new().expect("Failed to create mDNS daemon");
        let service_type = "_osc._udp.local.";
        let receiver = mdns
            .browse(service_type)
            .expect("Failed to browse for OSC services");
        let mut event_stream = receiver.stream();
        log::info!("mDNS listener starting.");

        let nel_state: State<NelAppState> = app_handle.state::<NelAppState>().clone();
...```

Later, when the IP gets resolved, I want to write that into the state , but I cannot figure out how.

```Rust
...
       let apu_remote = ApuRemote {
                                fullname: fullname.to_string(),
                                address,
                                port: info.get_port(),
                            };

                            nel_state.apu_remote = apu_remote.clone();   <--

error[E0594]: cannot assign to data in dereference of `tauri::State<'_, NelAppState>`
  --> src/udp/mdns.rs:55:29
   |
55 | ...                   nel_state.apu_remote = apu_remote.clone();
   |                       ^^^^^^^^^^^^^^^^^^^^ cannot assign
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `tauri::State<'_, NelAppState>`
...```
robust kraken
#

@broken owl take a look here (https://v2.tauri.app/develop/state-management/#mutability). Maybe it can help with state management between threads using mutexes.

Other two points in your code:

  • I think you'll need to make nel_state mutable in order to change it's internal fields.
  • I'm not sure about the reasons, but I think that you need first assign app_handle.state::<NelAppState>() to a variable and then assign a clone() of this variable instead of trying to clone app_handle.state::<NelAppState>() directly. I had some issues like this trying to do like you did.
  • When you're assigning the value of a variable that won't be needed afterwards, you can assign it directly instead of assigning a clone() (remove the clone() in the line: nel_state.apu_remote = apu_remote.clone();)
Tauri

The cross-platform app building toolkit