#Send event from Rust to Frontend (js)

6 messages · Page 1 of 1 (latest)

solar jungle
#

It's not that complicated

#[tauri::command]
async fn setup(
    window: tauri::Window,
    system_state_mutex: State<'_, Arc<Mutex<SystemState>>>,
) -> Result<(), Error> {
    println!("Setting up listeners");
    let state = Arc::clone(&system_state_mutex);
    std::thread::spawn(move || -> Result<(), Error> {
        loop {            std::thread::sleep(std::time::Duration::from_secs(1));
            window                .emit("system_state_update", state.lock()?.clone())
                .unwrap();
        }
    });
    Ok(())
}

Then invoke it


    const self = this
    self.unlisten = await listen('system_state_update', (event) => {
      self.systemState = event.payload
    })
    await invoke('setup')

In a phone call I'll write an alternative in a moment

#

Well spawning a new thread is always going to be a thing
And yea that's also one alternative. I mainly use the command version because then I can know the listener is set up before events start emitting

#

This is one alternative for setting an AppHandle globally available, and then using app.get_window("LABEL") to get the desired window later

// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use once_cell::sync::OnceCell;
use tauri::Manager;

static APP: OnceCell<tauri::AppHandle> = OnceCell::new();

fn something() {
    let app = APP.get().unwrap();
    let window = app.get_window("main").unwrap();
}

fn main() {
    tauri::Builder::default()
        .setup(|app| {
            APP.set(app.handle()).expect("error initializing tauri app");
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
#

As long as you have access to an AppHandle you can access basically anything in your app