tauri-docs icon indicating copy to clipboard operation
tauri-docs copied to clipboard

Command mutable atomic state

Open regnisolbap opened this issue 4 years ago • 0 comments

It would be nice to add an example of mutable atomic state to the tauri::app::manage docs like:

use tauri::State;

// here we use AtomicBool to achieve interior mutability
struct IsAuthenticated(AtomicBool);

#[tauri::command]
fn authenticate(is_authenticated: State<IsAuthenticated>) {
  // authenticate, mutating the state with AtomicBool::store
  is_authenticated.0.store(true, Ordering::SeqCst);
}

#[tauri::command]
fn check_authentication(is_authenticated: State<IsAuthenticated>) -> bool {
  // check is_authenticated state with AtomicBool::load
  is_authenticated.0.load(Ordering::SeqCst)
}

fn main() {
  Builder::default()
    .manage(IsAuthenticated(AtomicBool::new(false)))
    .invoke_handler(tauri::generate_handler![authenticate, check_authentication])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

Maybe also it could be useful to have every example from the docs of that tauri::app::manage function in the Create Rust Commands guide. Finally, worth mentioning that state could be accessed from a Manager impl (eg. app inside the setup function) with manager.state::<T>().

regnisolbap avatar Jul 02 '21 12:07 regnisolbap