From 23c215da0218281db7e342e053e1709b4ae3495d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Sep 2023 14:11:13 -0500 Subject: [PATCH] make RuntimeGuard public --- packages/core/src/runtime.rs | 81 +++++++++++++++--------------------- 1 file changed, 34 insertions(+), 47 deletions(-) diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 4b9dcdab0..566e9ba7c 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -7,51 +7,6 @@ thread_local! { static RUNTIMES: RefCell>> = RefCell::new(vec![]); } -/// Run some code within a runtime -pub fn in_runtime(runtime: Rc, f: impl FnOnce() -> R) -> R { - let _guard = RuntimeGuard::new(runtime); - f() -} - -/// Override the current runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime. -/// -/// ```rust -/// use dioxus::prelude::*; -/// -/// fn main() { -/// let virtual_dom = VirtualDom::new(app); -/// } -/// -/// fn app(cx: Scope) -> Element { -/// render!{ Component { runtime: Runtime::current().unwrap() } } -/// } -/// -/// // In a dynamic library -/// #[derive(Props)] -/// struct ComponentProps { -/// runtime: std::rc::Rc, -/// } -/// -/// impl PartialEq for ComponentProps { -/// fn eq(&self, _other: &Self) -> bool { -/// true -/// } -/// } -/// -/// fn Component(cx: Scope) -> Element { -/// cx.use_hook(|| override_runtime(cx.props.runtime.clone())); -/// -/// render! { div {} } -/// } -/// ``` -pub fn override_runtime(runtime: Rc) { - RUNTIMES.with(|stack| { - let mut stack = stack.borrow_mut(); - stack.pop(); - stack.push(runtime); - }); -} - /// Pushes a new scope onto the stack pub(crate) fn push_runtime(runtime: Rc) { RUNTIMES.with(|stack| stack.borrow_mut().push(runtime)); @@ -143,10 +98,42 @@ impl Runtime { } } -pub(crate) struct RuntimeGuard(Rc); +/// A gaurd for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime. +/// +/// ```rust +/// use dioxus::prelude::*; +/// +/// fn main() { +/// let virtual_dom = VirtualDom::new(app); +/// } +/// +/// fn app(cx: Scope) -> Element { +/// render!{ Component { runtime: Runtime::current().unwrap() } } +/// } +/// +/// // In a dynamic library +/// #[derive(Props)] +/// struct ComponentProps { +/// runtime: std::rc::Rc, +/// } +/// +/// impl PartialEq for ComponentProps { +/// fn eq(&self, _other: &Self) -> bool { +/// true +/// } +/// } +/// +/// fn Component(cx: Scope) -> Element { +/// cx.use_hook(|| RuntimeGuard::new(cx.props.runtime.clone())); +/// +/// render! { div {} } +/// } +/// ``` +pub struct RuntimeGuard(Rc); impl RuntimeGuard { - pub(crate) fn new(runtime: Rc) -> Self { + /// Create a new runtime guard that sets the current Dioxus runtime. The runtime will be reset when the guard is dropped + pub fn new(runtime: Rc) -> Self { push_runtime(runtime.clone()); Self(runtime) }