Emit change to frontend from rust?! #7558
-
I'm working on a serial monitor app with Tauri and I'm trying to figure out how I can use an event to emit change to the frontend. I'm aware of the example listed in the docs, but this seems to only be a solution for the setup only. The serial data is getting updated from a tokio thread and will print whenever there are new serial data. My current solution is to keep pinging the backend for any new serial data every 25ms. As you can imagine I'm not satisfied with this solution. Let me know if anyone has encountered this or has some solutions they could share. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Well, not reallyyy. All you need is access to an AppHandle or Window instance (which you can get from the setup hook, all the event handlers, and tauri commands). If for some reason you can't move an AppHandle into the tokio thread you could look into a |
Beta Was this translation helpful? Give feedback.
-
Success! This was exactly what I needed. If anyone is curious allow me to share my findings. In the rust, I was able to create a command and pass in the app handle as a parameter. // define the payload struct
#[derive(Clone, serde::Serialize)]
struct Payload {
message: String,
}
// make the command
#[tauri::command]
async fn test_app_handle(app: tauri::AppHandle) {
app.emit_all("event-name", Payload { message: "Tauri is awesome!".into() }).unwrap();
} In the frontend, we need to start listening for the event. This is how I set it up using typescript // same type as payload
type Payload = {
message: string;
};
async function startSerialEventListener() {
await listen<Payload>('event-name', (event) => {
console.log("Event triggered from rust!\nPayload: " + event.payload.message);
});
} After I defined these I created a button on the frontend that starts listening to the event and calls the tauri command. This will trigger the listener and print your message to the console log. I hope this helps anyone with the same issue. Thanks for the save @FabianLars |
Beta Was this translation helpful? Give feedback.
Well, not reallyyy. All you need is access to an AppHandle or Window instance (which you can get from the setup hook, all the event handlers, and tauri commands). If for some reason you can't move an AppHandle into the tokio thread you could look into a
OnceCell
(part of the latest rust version or the once_cell crate) to make a global-ish AppHandle.