diff --git a/.changes/try-state.md b/.changes/try-state.md new file mode 100644 index 000000000..d59192098 --- /dev/null +++ b/.changes/try-state.md @@ -0,0 +1,5 @@ +--- +"tauri": patch +--- + +Add `try_state` API to the `Manager` trait. diff --git a/core/tauri/src/lib.rs b/core/tauri/src/lib.rs index 2105e6dd6..a092a0b7f 100644 --- a/core/tauri/src/lib.rs +++ b/core/tauri/src/lib.rs @@ -308,7 +308,7 @@ pub trait Manager: sealed::ManagerBase { self.manager().state().set(state); } - /// Gets the managed state for the type `T`. + /// Gets the managed state for the type `T`. Panics if the type is not managed. fn state(&self) -> State<'_, T> where T: Send + Sync + 'static, @@ -316,6 +316,14 @@ pub trait Manager: sealed::ManagerBase { self.manager().inner.state.get() } + /// Tries to get the managed state for the type `T`. Returns `None` if the type is not managed. + fn try_state(&self) -> Option> + where + T: Send + Sync + 'static, + { + self.manager().inner.state.try_get() + } + /// Adds a plugin to the runtime. fn plugin + 'static>(&self, plugin: P) { self diff --git a/core/tauri/src/state.rs b/core/tauri/src/state.rs index 8d010b567..7fd5b8c3a 100644 --- a/core/tauri/src/state.rs +++ b/core/tauri/src/state.rs @@ -60,4 +60,9 @@ impl StateManager { pub fn get(&self) -> State<'_, T> { State(self.0.get()) } + + /// Gets the state associated with the specified type. + pub fn try_get(&self) -> Option> { + self.0.try_get().map(State) + } }