From fd92079eb3d33b18b4edd38529cace5ff446a992 Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Sun, 1 Jan 2023 22:09:08 -0500 Subject: [PATCH] feat: add recycling of rts in signals --- examples/signals.rs | 6 +----- packages/signals/src/rt.rs | 36 +++++++++++++++++++++--------------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/examples/signals.rs b/examples/signals.rs index 17ae40b73..e5e0935b5 100644 --- a/examples/signals.rs +++ b/examples/signals.rs @@ -1,7 +1,3 @@ -//! Example: README.md showcase -//! -//! The example from the README.md. - use dioxus::prelude::*; use dioxus_signals::{use_init_signal_rt, use_signal}; use std::time::Duration; @@ -15,7 +11,7 @@ fn app(cx: Scope) -> Element { let mut count = use_signal(cx, || 0); - use_coroutine(cx, |_: UnboundedReceiver<()>| async move { + use_future!(cx, || async move { loop { count += 1; tokio::time::sleep(Duration::from_millis(100)).await; diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index c24e336f9..d516b9ff0 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -1,27 +1,33 @@ -use std::{ - any::Any, - cell::RefCell, - rc::Rc, - sync::{Arc, Mutex}, -}; +use std::{any::Any, cell::RefCell, sync::Arc}; use dioxus_core::ScopeId; use slab::Slab; +thread_local! { + static RUNTIMES: RefCell> = RefCell::new(Vec::new()); +} + /// Provide the runtime for signals /// /// This will reuse dead runtimes pub fn claim_rt(update_any: Arc) -> &'static SignalRt { - Box::leak(Box::new(SignalRt { - signals: RefCell::new(Slab::new()), - update_any, - })) + RUNTIMES.with(|runtimes| { + if let Some(rt) = runtimes.borrow_mut().pop() { + return rt; + } + + Box::leak(Box::new(SignalRt { + signals: RefCell::new(Slab::new()), + update_any, + })) + }) } -pub fn reclam_rt(rt: usize) {} - -struct GlobalRt { - signals: Slab, +/// Push this runtime into the global runtime list +pub fn reclam_rt(_rt: &'static SignalRt) { + RUNTIMES.with(|runtimes| { + runtimes.borrow_mut().push(_rt); + }); } pub struct SignalRt { @@ -78,7 +84,7 @@ impl SignalRt { } pub(crate) fn write(&self, id: usize) -> std::cell::RefMut { - let mut signals = self.signals.borrow_mut(); + let signals = self.signals.borrow_mut(); std::cell::RefMut::map(signals, |signals| { signals[id].value.downcast_mut::().unwrap() })