subscribe.rs 2.2 KB

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