瀏覽代碼

feat: add recycling of rts in signals

Jonathan Kelley 2 年之前
父節點
當前提交
fd92079eb3
共有 2 個文件被更改,包括 22 次插入20 次删除
  1. 1 5
      examples/signals.rs
  2. 21 15
      packages/signals/src/rt.rs

+ 1 - 5
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;

+ 21 - 15
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<Vec<&'static SignalRt>> = RefCell::new(Vec::new());
+}
+
 /// Provide the runtime for signals
 ///
 /// This will reuse dead runtimes
 pub fn claim_rt(update_any: Arc<dyn Fn(ScopeId)>) -> &'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;
+        }
 
-pub fn reclam_rt(rt: usize) {}
+        Box::leak(Box::new(SignalRt {
+            signals: RefCell::new(Slab::new()),
+            update_any,
+        }))
+    })
+}
 
-struct GlobalRt {
-    signals: Slab<Inner>,
+/// 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<T: 'static>(&self, id: usize) -> std::cell::RefMut<T> {
-        let mut signals = self.signals.borrow_mut();
+        let signals = self.signals.borrow_mut();
         std::cell::RefMut::map(signals, |signals| {
             signals[id].value.downcast_mut::<T>().unwrap()
         })