tauri_plugin_sync_state/
ext.rs1use crate::{
2 commands::event_name,
3 error::{Error, Result},
4 slice::{StateRegistry, SyncState},
5};
6use tauri::{Emitter, Manager, Runtime};
7
8pub trait SyncStateExt<R: Runtime> {
9 fn sync_read<S: SyncState>(&self) -> Result<S>;
10 fn sync_mutate<S: SyncState>(&self, f: impl FnOnce(&mut S)) -> Result<()>;
11}
12
13impl<R: Runtime, T: Manager<R> + Emitter<R>> SyncStateExt<R> for T {
14 fn sync_read<S: SyncState>(&self) -> Result<S> {
15 self.state::<StateRegistry>().read::<S>()
16 }
17 fn sync_mutate<S: SyncState>(&self, f: impl FnOnce(&mut S)) -> Result<()> {
18 let next = self.state::<StateRegistry>().mutate::<S>(f)?;
19 self.emit(&event_name(S::NAME), next)
20 .map_err(|e| Error::Emit(e.to_string()))
21 }
22}