Share State Across Tauri Commands | Mutex AppState Tutorial
About this lesson
Most Tauri 2 examples show you a single command with no state. Real apps need shared state — one piece of data that multiple commands read and mutate, consistently, without races. The canonical pattern is a Mutex around an AppState struct on the builder via .manage(), injected into every command through the State extractor. Source code: https://github.com/GoCelesteAI/tauri_tickr We build Tickr, a stopwatch with three fields that must move together — running, elapsed_ms, and started_at. Start ticks the clock. Stop pauses and folds the run's duration into the millisecond counter. Start again resumes from where it left off. The Mutex is what keeps those three fields honest across every Start/Stop cycle. What You'll Learn: - Mutex around an AppState struct as the canonical pattern for shared mutable state in Tauri 2 — why a Mutex around a struct beats three separate Atomics when fields are coupled. - tauri::Builder::default().manage(...) — registers the state once, makes it available to every command. - The State extractor as a command parameter — pulls your managed type out of the registry. Tauri injects it; you just declare it. - state.lock().unwrap() — locking the Mutex inside a command body. Why unwrap is fine for app-owned state (poisoning means a previous handler panicked, which is a bug you want loud). - invoke_handler(tauri::generate_handler![...]) — wiring custom commands so the frontend invoke("name") can find them. - setInterval calling invoke("get_elapsed") — the polling pattern. When you need a refreshing readout, polling at 50ms is simpler than events and fast enough for human eyes. - When to reach for std Mutex vs RwLock vs parking_lot::Mutex — the std Mutex is the right default; reach for alternatives only when you have measured contention. Timestamps: 0:00 - The proof: Start, Stop, Start again continues from where it stopped 0:24 - lib.rs — AppState struct and why a Mutex around it 1:00 - start, stop, reset commands — three coupled fields 2:30 - ge
DeepCamp AI