Selaa lähdekoodia

feat(core): `try_state` API on the `Manager` trait (#2341)

Lucas Fernandes Nogueira 4 vuotta sitten
vanhempi
sitoutus
84a0e04cbe
3 muutettua tiedostoa jossa 19 lisäystä ja 1 poistoa
  1. 5 0
      .changes/try-state.md
  2. 9 1
      core/tauri/src/lib.rs
  3. 5 0
      core/tauri/src/state.rs

+ 5 - 0
.changes/try-state.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Add `try_state` API to the `Manager` trait.

+ 9 - 1
core/tauri/src/lib.rs

@@ -308,7 +308,7 @@ pub trait Manager<R: Runtime>: sealed::ManagerBase<R> {
     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<T>(&self) -> State<'_, T>
   where
     T: Send + Sync + 'static,
@@ -316,6 +316,14 @@ pub trait Manager<R: Runtime>: sealed::ManagerBase<R> {
     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<T>(&self) -> Option<State<'_, T>>
+  where
+    T: Send + Sync + 'static,
+  {
+    self.manager().inner.state.try_get()
+  }
+
   /// Adds a plugin to the runtime.
   fn plugin<P: plugin::Plugin<R> + 'static>(&self, plugin: P) {
     self

+ 5 - 0
core/tauri/src/state.rs

@@ -60,4 +60,9 @@ impl StateManager {
   pub fn get<T: Send + Sync + 'static>(&self) -> State<'_, T> {
     State(self.0.get())
   }
+
+  /// Gets the state associated with the specified type.
+  pub fn try_get<T: Send + Sync + 'static>(&self) -> Option<State<'_, T>> {
+    self.0.try_get().map(State)
+  }
 }