You can trigger events from your Rust backend to your TypeScript frontend with full type safety. The #[taurpc::procedures] macro automatically generates an event trigger struct.
By default, the trigger struct is named TauRpc{TraitName}EventTrigger. You can customize this name using the event_trigger attribute on the trait.
To define an event, add the #[taurpc(event)] attribute to the method in your trait. Methods marked with #[taurpc(event)] do not require a corresponding resolver implementation.
On the frontend, use the .on() method provided by the generated proxy to listen for these events. The .on() method returns an unlisten function that should be called during component cleanup (e.g., useEffect cleanup in React or onDestroy in Svelte).
// 1. Define the API and custom trigger name
#[taurpc::procedures(event_trigger = ApiEventTrigger)]
trait Api {
#[taurpc(event)]
async fn hello_world();
}
#[derive(Clone)]
struct ApiImpl;
#[taurpc::resolvers]
impl Api for ApiImpl {}
#[tokio::main]
async fn main() {
tauri::Builder::default()
.invoke_handler(taurpc::create_ipc_handler(ApiImpl.into_handler()))
.setup(|app| {
// 2. Use the trigger in the setup block
let trigger = ApiEventTrigger::new(app.handle());
trigger.hello_world()?;
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// 3. Listen on the frontend
const unlisten = await taurpc.hello_world.on(() => {
console.log('Hello World!')
})
// Cleanup
unlisten()