From 598fb44f8b46f1fe16a36ac3729ab689a23ea509 Mon Sep 17 00:00:00 2001 From: Filipe Rodrigues Date: Tue, 5 Mar 2024 18:47:45 +0000 Subject: [PATCH] Added `AsyncSignal::with_inner`. --- dynatos-reactive/src/async_signal.rs | 46 +++++++++++++++++----------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/dynatos-reactive/src/async_signal.rs b/dynatos-reactive/src/async_signal.rs index 46bedc7..e26ee28 100644 --- a/dynatos-reactive/src/async_signal.rs +++ b/dynatos-reactive/src/async_signal.rs @@ -86,6 +86,31 @@ impl AsyncSignal { }); Self { inner } } + + /// Uses the inner value, without polling the future. + // TODO: Better name that indicates that we don't poll? + pub fn with_inner(&self, f: F2) -> O + where + F2: for<'a> FnOnce(Option<&'a F::Output>) -> O, + { + // If there's an effect running, add it to the subscribers + if let Some(effect) = effect::running() { + self.inner.waker.trigger.add_subscriber(effect); + } + + // Then use the value + let value = self.inner.value.borrow(); + match &*value { + Some(value) => f(Some(value)), + None => { + // Note: We can't have `value` borrowed if it's `None`, or else + // our branch above to initialize wouldn't be able to write + // the value if we're being used recursively. + mem::drop(value); + f(None) + }, + } + } } impl Clone for AsyncSignal { @@ -116,12 +141,7 @@ where where F2: for<'a> FnOnce(Self::Value<'a>) -> O, { - // If there's an effect running, add it to the subscribers - if let Some(effect) = effect::running() { - self.inner.waker.trigger.add_subscriber(effect); - } - - // Then try to poll the future, if we don't have a value yet + // Try to poll the future, if we don't have a value yet if self.inner.value.borrow().is_none() { // Get the inner future through pin-project + pin-cell. let inner = self.inner.as_ref().project_ref(); @@ -136,18 +156,8 @@ where } } - // Finally use the value - let value = self.inner.value.borrow(); - match &*value { - Some(value) => f(Some(value)), - None => { - // Note: We can't have `value` borrowed if it's `None`, or else - // our branch above to initialize wouldn't be able to write - // the value if we're being used recursively. - mem::drop(value); - f(None) - }, - } + // Then use the value + self.with_inner(f) } }