From 555f4d583413db983cfe15cf02c959bc5cdf0ad6 Mon Sep 17 00:00:00 2001 From: Daniel Albl <66034631+DanielAlbl@users.noreply.github.com> Date: Tue, 15 Aug 2023 12:27:19 -0600 Subject: [PATCH] Add 'with' and 'with_mut' to 'use_shared_state' (#1353) --- packages/hooks/src/use_shared_state.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/hooks/src/use_shared_state.rs b/packages/hooks/src/use_shared_state.rs index 019d55942..b900b9dc6 100644 --- a/packages/hooks/src/use_shared_state.rs +++ b/packages/hooks/src/use_shared_state.rs @@ -282,6 +282,20 @@ impl UseSharedState { ), } } + + /// Take a reference to the inner value temporarily and produce a new value + #[cfg_attr(debug_assertions, track_caller)] + #[cfg_attr(debug_assertions, inline(never))] + pub fn with(&self, immutable_callback: impl FnOnce(&T) -> O) -> O { + immutable_callback(&*self.read()) + } + + /// Take a mutable reference to the inner value temporarily and produce a new value + #[cfg_attr(debug_assertions, track_caller)] + #[cfg_attr(debug_assertions, inline(never))] + pub fn with_mut(&self, mutable_callback: impl FnOnce(&mut T) -> O) -> O { + mutable_callback(&mut *self.write()) + } } impl Clone for UseSharedState {