subscribe.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #![allow(unused, non_upper_case_globals, non_snake_case)]
  2. use dioxus_core::NoOpMutations;
  3. use std::collections::HashMap;
  4. use std::rc::Rc;
  5. use dioxus::prelude::*;
  6. use dioxus_core::ElementId;
  7. use dioxus_signals::*;
  8. use std::cell::RefCell;
  9. #[test]
  10. fn reading_subscribes() {
  11. tracing_subscriber::fmt::init();
  12. #[derive(Default)]
  13. struct RunCounter {
  14. parent: usize,
  15. children: HashMap<ScopeId, usize>,
  16. }
  17. let counter = Rc::new(RefCell::new(RunCounter::default()));
  18. let mut dom = VirtualDom::new_with_props(
  19. |props: Rc<RefCell<RunCounter>>| {
  20. let mut signal = use_signal(|| 0);
  21. println!("Parent: {:?}", current_scope_id());
  22. if generation() == 1 {
  23. signal += 1;
  24. }
  25. props.borrow_mut().parent += 1;
  26. rsx! {
  27. for id in 0..10 {
  28. Child {
  29. signal: signal,
  30. counter: props.clone()
  31. }
  32. }
  33. }
  34. },
  35. counter.clone(),
  36. );
  37. #[derive(Props, Clone)]
  38. struct ChildProps {
  39. signal: Signal<usize>,
  40. counter: Rc<RefCell<RunCounter>>,
  41. }
  42. impl PartialEq for ChildProps {
  43. fn eq(&self, other: &Self) -> bool {
  44. self.signal == other.signal
  45. }
  46. }
  47. fn Child(props: ChildProps) -> Element {
  48. println!("Child: {:?}", current_scope_id());
  49. *props
  50. .counter
  51. .borrow_mut()
  52. .children
  53. .entry(current_scope_id().unwrap())
  54. .or_default() += 1;
  55. rsx! {
  56. "{props.signal}"
  57. }
  58. }
  59. dom.rebuild_in_place();
  60. {
  61. let current_counter = counter.borrow();
  62. assert_eq!(current_counter.parent, 1);
  63. for (scope_id, rerun_count) in current_counter.children.iter() {
  64. assert_eq!(rerun_count, &1);
  65. }
  66. }
  67. dom.mark_dirty(ScopeId::APP);
  68. dom.render_immediate(&mut NoOpMutations);
  69. dom.render_immediate(&mut NoOpMutations);
  70. {
  71. let current_counter = counter.borrow();
  72. assert_eq!(current_counter.parent, 2);
  73. for (scope_id, rerun_count) in current_counter.children.iter() {
  74. assert_eq!(rerun_count, &2);
  75. }
  76. }
  77. }