only subscribe scopes to signals when rendering
This commit is contained in:
1 parent
49f3b8235d
commit
48751d2f98
14 files changed
+424
-48
No files matched your search
@@ -86,8 +86,12 @@ fn current_owner<S: Storage<T>, T>() -> Owner<S> {
|
||||
}
|
||||
|
||||
// Otherwise get the owner from the current reactive context.
|
||||
let current_reactive_context = ReactiveContext::current();
|
||||
owner_in_scope(current_reactive_context.origin_scope())
|
||||
match ReactiveContext::current(){
|
||||
Some(current_reactive_context) => owner_in_scope(current_reactive_context.origin_scope()),
|
||||
None => {
|
||||
owner_in_scope(current_scope_id().expect("in a virtual dom"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_in_scope<S: Storage<T>, T>(scope: ScopeId) -> Owner<S> {
|
||||
|
||||
@@ -33,7 +33,7 @@ impl<T: PartialEq + 'static> GlobalMemo<T> {
|
||||
None => {
|
||||
drop(read);
|
||||
// Constructors are always run in the root scope
|
||||
let signal = ScopeId::ROOT.in_runtime(|| Signal::selector(self.selector));
|
||||
let signal = ScopeId::ROOT.in_runtime(|| Signal::memo(self.selector));
|
||||
context.signal.borrow_mut().insert(key, Box::new(signal));
|
||||
signal
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use dioxus_core::prelude::{
|
||||
current_scope_id, has_context, provide_context, schedule_update_any, ScopeId,
|
||||
current_scope_id, has_context, provide_context, schedule_update_any, ScopeId
|
||||
};
|
||||
use generational_box::SyncStorage;
|
||||
use rustc_hash::FxHashSet;
|
||||
@@ -68,21 +68,24 @@ impl ReactiveContext {
|
||||
/// If this was set manually, then that value will be returned.
|
||||
///
|
||||
/// If there's no current reactive context, then a new one will be created for the current scope and returned.
|
||||
pub fn current() -> Self {
|
||||
pub fn current() -> Option<Self> {
|
||||
let cur = CURRENT.with(|current| current.borrow().last().cloned());
|
||||
|
||||
// If we're already inside a reactive context, then return that
|
||||
if let Some(cur) = cur {
|
||||
return cur;
|
||||
return Some(cur);
|
||||
}
|
||||
|
||||
// If we're rendering, then try and use the reactive context attached to this component
|
||||
if !dioxus_core::vdom_is_rendering(){
|
||||
return None;
|
||||
}
|
||||
if let Some(cx) = has_context() {
|
||||
return cx;
|
||||
return Some(cx);
|
||||
}
|
||||
|
||||
// Otherwise, create a new context at the current scope
|
||||
provide_context(ReactiveContext::new_for_scope(current_scope_id()))
|
||||
Some(provide_context(ReactiveContext::new_for_scope(current_scope_id())))
|
||||
}
|
||||
|
||||
/// Run this function in the context of this reactive context
|
||||
|
||||
@@ -90,19 +90,19 @@ impl<T: PartialEq + 'static> Signal<T> {
|
||||
///
|
||||
/// Selectors can be used to efficiently compute derived data from signals.
|
||||
#[track_caller]
|
||||
pub fn selector(f: impl FnMut() -> T + 'static) -> ReadOnlySignal<T> {
|
||||
Self::maybe_sync_memo(f)
|
||||
pub fn memo(f: impl FnMut() -> T + 'static) -> ReadOnlySignal<T> {
|
||||
Self::use_maybe_sync_memo(f)
|
||||
}
|
||||
|
||||
/// Creates a new Selector that may be Sync + Send. The selector will be run immediately and whenever any signal it reads changes.
|
||||
///
|
||||
/// Selectors can be used to efficiently compute derived data from signals.
|
||||
#[track_caller]
|
||||
pub fn maybe_sync_memo<S: Storage<SignalData<T>>>(
|
||||
pub fn use_maybe_sync_memo<S: Storage<SignalData<T>>>(
|
||||
mut f: impl FnMut() -> T + 'static,
|
||||
) -> ReadOnlySignal<T, S> {
|
||||
// Get the current reactive context
|
||||
let rc = ReactiveContext::current();
|
||||
let rc = ReactiveContext::new();
|
||||
|
||||
// Create a new signal in that context, wiring up its dependencies and subscribers
|
||||
let mut state: Signal<T, S> = rc.run_in(|| Signal::new_maybe_sync(f()));
|
||||
@@ -201,8 +201,9 @@ impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
|
||||
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||
let inner = self.inner.try_read()?;
|
||||
|
||||
let reactive_context = ReactiveContext::current();
|
||||
inner.subscribers.lock().unwrap().insert(reactive_context);
|
||||
if let Some(reactive_context) = ReactiveContext::current(){
|
||||
inner.subscribers.lock().unwrap().insert(reactive_context);
|
||||
}
|
||||
|
||||
Ok(S::map(inner, |v| &v.value))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
#![allow(unused, non_upper_case_globals, non_snake_case)]
|
||||
|
||||
use dioxus_core::NoOpMutations;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::ElementId;
|
||||
use dioxus_signals::*;
|
||||
|
||||
#[test]
|
||||
fn create_signals_global() {
|
||||
let mut dom = VirtualDom::new(|| {
|
||||
rsx! {
|
||||
for _ in 0..10 {
|
||||
Child {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fn Child() -> Element {
|
||||
let signal = create_without_cx();
|
||||
|
||||
rsx! {
|
||||
"{signal}"
|
||||
}
|
||||
}
|
||||
|
||||
dom.rebuild_in_place();
|
||||
|
||||
fn create_without_cx() -> Signal<String> {
|
||||
Signal::new("hello world".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deref_signal() {
|
||||
let mut dom = VirtualDom::new(|| {
|
||||
rsx! {
|
||||
for _ in 0..10 {
|
||||
Child {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fn Child() -> Element {
|
||||
let signal = Signal::new("hello world".to_string());
|
||||
|
||||
// You can call signals like functions to get a Ref of their value.
|
||||
assert_eq!(&*signal(), "hello world");
|
||||
|
||||
rsx! {
|
||||
"hello world"
|
||||
}
|
||||
}
|
||||
|
||||
dom.rebuild_in_place();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_signals() {
|
||||
let mut dom = VirtualDom::new(|| {
|
||||
let generation = generation();
|
||||
|
||||
let count = if generation % 2 == 0 { 10 } else { 0 };
|
||||
rsx! {
|
||||
for _ in 0..count {
|
||||
Child {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fn Child() -> Element {
|
||||
let signal = create_without_cx();
|
||||
|
||||
rsx! {
|
||||
"{signal}"
|
||||
}
|
||||
}
|
||||
|
||||
dom.rebuild_in_place();
|
||||
dom.mark_dirty(ScopeId::ROOT);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
|
||||
fn create_without_cx() -> Signal<String> {
|
||||
Signal::new("hello world".to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
#![allow(unused, non_upper_case_globals, non_snake_case)]
|
||||
use dioxus_core::NoOpMutations;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use dioxus::html::p;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::ElementId;
|
||||
use dioxus_signals::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn memos_rerun() {
|
||||
let _ = simple_logger::SimpleLogger::new().init();
|
||||
|
||||
#[derive(Default)]
|
||||
struct RunCounter {
|
||||
component: usize,
|
||||
effect: usize,
|
||||
}
|
||||
|
||||
let counter = Rc::new(RefCell::new(RunCounter::default()));
|
||||
let mut dom = VirtualDom::new_with_props(
|
||||
|counter: Rc<RefCell<RunCounter>>| {
|
||||
counter.borrow_mut().component += 1;
|
||||
|
||||
let mut signal = use_signal(|| 0);
|
||||
let memo = use_hook(move || {
|
||||
to_owned![counter];
|
||||
Signal::memo(move || {
|
||||
counter.borrow_mut().effect += 1;
|
||||
println!("Signal: {:?}", signal);
|
||||
signal()
|
||||
})
|
||||
});
|
||||
assert_eq!(memo(), 0);
|
||||
signal += 1;
|
||||
assert_eq!(memo(), 1);
|
||||
|
||||
rsx! {
|
||||
div {}
|
||||
}
|
||||
},
|
||||
counter.clone(),
|
||||
);
|
||||
|
||||
dom.rebuild_in_place();
|
||||
|
||||
let current_counter = counter.borrow();
|
||||
assert_eq!(current_counter.component, 1);
|
||||
assert_eq!(current_counter.effect, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memos_prevents_component_rerun() {
|
||||
let _ = simple_logger::SimpleLogger::new().init();
|
||||
|
||||
#[derive(Default)]
|
||||
struct RunCounter {
|
||||
component: usize,
|
||||
memo: usize,
|
||||
}
|
||||
|
||||
let counter = Rc::new(RefCell::new(RunCounter::default()));
|
||||
let mut dom = VirtualDom::new_with_props(
|
||||
|props: Rc<RefCell<RunCounter>>| {
|
||||
let mut signal = use_signal(|| 0);
|
||||
|
||||
if generation() == 1 {
|
||||
*signal.write() = 0;
|
||||
}
|
||||
if generation() == 2 {
|
||||
println!("Writing to signal");
|
||||
*signal.write() = 1;
|
||||
}
|
||||
|
||||
rsx! {
|
||||
Child {
|
||||
signal: signal,
|
||||
counter: props.clone(),
|
||||
}
|
||||
}
|
||||
},
|
||||
counter.clone(),
|
||||
);
|
||||
|
||||
#[derive(Default, Props, Clone)]
|
||||
struct ChildProps {
|
||||
signal: Signal<usize>,
|
||||
counter: Rc<RefCell<RunCounter>>,
|
||||
}
|
||||
|
||||
impl PartialEq for ChildProps {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.signal == other.signal
|
||||
}
|
||||
}
|
||||
|
||||
fn Child(props: ChildProps) -> Element {
|
||||
let counter = &props.counter;
|
||||
let signal = props.signal;
|
||||
counter.borrow_mut().component += 1;
|
||||
|
||||
let memo = use_hook(move || {
|
||||
to_owned![counter];
|
||||
Signal::memo(move || {
|
||||
counter.borrow_mut().memo += 1;
|
||||
println!("Signal: {:?}", signal);
|
||||
signal()
|
||||
})
|
||||
});
|
||||
match generation() {
|
||||
0 => {
|
||||
assert_eq!(memo(), 0);
|
||||
}
|
||||
1 => {
|
||||
assert_eq!(memo(), 1);
|
||||
}
|
||||
_ => panic!("Unexpected generation"),
|
||||
}
|
||||
|
||||
rsx! {
|
||||
div {}
|
||||
}
|
||||
}
|
||||
|
||||
dom.rebuild_in_place();
|
||||
dom.mark_dirty(ScopeId::ROOT);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
|
||||
{
|
||||
let current_counter = counter.borrow();
|
||||
assert_eq!(current_counter.component, 1);
|
||||
assert_eq!(current_counter.memo, 2);
|
||||
}
|
||||
|
||||
dom.mark_dirty(ScopeId::ROOT);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
|
||||
{
|
||||
let current_counter = counter.borrow();
|
||||
assert_eq!(current_counter.component, 2);
|
||||
assert_eq!(current_counter.memo, 3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
#![allow(unused, non_upper_case_globals, non_snake_case)]
|
||||
|
||||
use dioxus_core::NoOpMutations;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::ElementId;
|
||||
use dioxus_signals::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn reading_subscribes() {
|
||||
simple_logger::SimpleLogger::new().init().unwrap();
|
||||
|
||||
#[derive(Default)]
|
||||
struct RunCounter {
|
||||
parent: usize,
|
||||
children: HashMap<ScopeId, usize>,
|
||||
}
|
||||
|
||||
let counter = Rc::new(RefCell::new(RunCounter::default()));
|
||||
let mut dom = VirtualDom::new_with_props(
|
||||
|props: Rc<RefCell<RunCounter>>| {
|
||||
let mut signal = use_signal(|| 0);
|
||||
|
||||
println!("Parent: {:?}", current_scope_id());
|
||||
if generation() == 1 {
|
||||
signal += 1;
|
||||
}
|
||||
|
||||
props.borrow_mut().parent += 1;
|
||||
|
||||
rsx! {
|
||||
for id in 0..10 {
|
||||
Child {
|
||||
signal: signal,
|
||||
counter: props.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
counter.clone(),
|
||||
);
|
||||
|
||||
#[derive(Props, Clone)]
|
||||
struct ChildProps {
|
||||
signal: Signal<usize>,
|
||||
counter: Rc<RefCell<RunCounter>>,
|
||||
}
|
||||
|
||||
impl PartialEq for ChildProps {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.signal == other.signal
|
||||
}
|
||||
}
|
||||
|
||||
fn Child(props: ChildProps) -> Element {
|
||||
println!("Child: {:?}", current_scope_id());
|
||||
*props
|
||||
.counter
|
||||
.borrow_mut()
|
||||
.children
|
||||
.entry(current_scope_id().unwrap())
|
||||
.or_default() += 1;
|
||||
|
||||
rsx! {
|
||||
"{props.signal}"
|
||||
}
|
||||
}
|
||||
|
||||
dom.rebuild_in_place();
|
||||
|
||||
{
|
||||
let current_counter = counter.borrow();
|
||||
assert_eq!(current_counter.parent, 1);
|
||||
|
||||
for (scope_id, rerun_count) in current_counter.children.iter() {
|
||||
assert_eq!(rerun_count, &1);
|
||||
}
|
||||
}
|
||||
|
||||
dom.mark_dirty(ScopeId::ROOT);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
dom.render_immediate(&mut NoOpMutations);
|
||||
|
||||
{
|
||||
let current_counter = counter.borrow();
|
||||
assert_eq!(current_counter.parent, 2);
|
||||
|
||||
for (scope_id, rerun_count) in current_counter.children.iter() {
|
||||
assert_eq!(rerun_count, &2);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user