task.rs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
  2. use std::{sync::atomic::AtomicUsize, time::Duration};
  3. use dioxus::prelude::*;
  4. async fn run_vdom(app: fn() -> Element) {
  5. let mut dom = VirtualDom::new(app);
  6. dom.rebuild(&mut dioxus_core::NoOpMutations);
  7. tokio::select! {
  8. _ = dom.wait_for_work() => {}
  9. _ = tokio::time::sleep(Duration::from_millis(500)) => {}
  10. };
  11. }
  12. #[tokio::test]
  13. async fn running_async() {
  14. static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
  15. fn app() -> Element {
  16. use_hook(|| {
  17. spawn(async {
  18. for x in 0..10 {
  19. tokio::time::sleep(Duration::from_micros(50)).await;
  20. POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
  21. }
  22. });
  23. spawn(async {
  24. for x in 0..10 {
  25. tokio::time::sleep(Duration::from_micros(25)).await;
  26. POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
  27. }
  28. });
  29. });
  30. rsx!({})
  31. }
  32. run_vdom(app).await;
  33. // By the time the tasks are finished, we should've accumulated ticks from two tasks
  34. // Be warned that by setting the delay to too short, tokio might not schedule in the tasks
  35. assert_eq!(
  36. POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed),
  37. 135
  38. );
  39. }
  40. /// Prove that yield_now doesn't cause a deadlock
  41. #[tokio::test]
  42. async fn yield_now_works() {
  43. thread_local! {
  44. static SEQUENCE: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
  45. }
  46. fn app() -> Element {
  47. // these two tasks should yield to eachother
  48. use_hook(|| {
  49. spawn(async move {
  50. for _ in 0..10 {
  51. tokio::task::yield_now().await;
  52. SEQUENCE.with(|s| s.borrow_mut().push(1));
  53. }
  54. })
  55. });
  56. use_hook(|| {
  57. spawn(async move {
  58. for _ in 0..10 {
  59. tokio::task::yield_now().await;
  60. SEQUENCE.with(|s| s.borrow_mut().push(2));
  61. }
  62. })
  63. });
  64. rsx!({})
  65. }
  66. run_vdom(app).await;
  67. SEQUENCE.with(|s| assert_eq!(s.borrow().len(), 20));
  68. }
  69. /// Ensure that calling wait_for_flush waits for dioxus to finish its synchronous work
  70. #[tokio::test]
  71. async fn flushing() {
  72. thread_local! {
  73. static SEQUENCE: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
  74. static BROADCAST: (tokio::sync::broadcast::Sender<()>, tokio::sync::broadcast::Receiver<()>) = tokio::sync::broadcast::channel(1);
  75. }
  76. fn app() -> Element {
  77. if generation() > 0 {
  78. println!("App");
  79. SEQUENCE.with(|s| s.borrow_mut().push(0));
  80. }
  81. // The next two tasks mimic effects. They should only be run after the app has been rendered
  82. use_hook(|| {
  83. spawn(async move {
  84. let mut channel = BROADCAST.with(|b| b.1.resubscribe());
  85. for _ in 0..10 {
  86. wait_for_next_render().await;
  87. println!("Task 1 recved");
  88. channel.recv().await.unwrap();
  89. println!("Task 1");
  90. SEQUENCE.with(|s| s.borrow_mut().push(1));
  91. }
  92. })
  93. });
  94. use_hook(|| {
  95. spawn(async move {
  96. let mut channel = BROADCAST.with(|b| b.1.resubscribe());
  97. for _ in 0..10 {
  98. wait_for_next_render().await;
  99. println!("Task 2 recved");
  100. channel.recv().await.unwrap();
  101. println!("Task 2");
  102. SEQUENCE.with(|s| s.borrow_mut().push(2));
  103. }
  104. })
  105. });
  106. rsx! {}
  107. }
  108. let mut dom = VirtualDom::new(app);
  109. dom.rebuild(&mut dioxus_core::NoOpMutations);
  110. let fut = async {
  111. // Trigger the flush by waiting for work
  112. for i in 0..10 {
  113. BROADCAST.with(|b| b.0.send(()).unwrap());
  114. dom.mark_dirty(ScopeId(0));
  115. dom.wait_for_work().await;
  116. dom.render_immediate(&mut dioxus_core::NoOpMutations);
  117. println!("Flushed {}", i);
  118. }
  119. BROADCAST.with(|b| b.0.send(()).unwrap());
  120. dom.wait_for_work().await;
  121. };
  122. tokio::select! {
  123. _ = fut => {}
  124. _ = tokio::time::sleep(Duration::from_millis(500)) => {
  125. println!("Aborting due to timeout");
  126. }
  127. };
  128. SEQUENCE.with(|s| {
  129. let s = s.borrow();
  130. println!("{:?}", s);
  131. assert_eq!(s.len(), 30);
  132. // We need to check if every three elements look like [0, 1, 2] or [0, 2, 1]
  133. let mut has_seen_1 = false;
  134. for (i, &x) in s.iter().enumerate() {
  135. let stage = i % 3;
  136. if stage == 0 {
  137. assert_eq!(x, 0);
  138. } else if stage == 1 {
  139. assert!(x == 1 || x == 2);
  140. has_seen_1 = x == 1;
  141. } else if stage == 2 {
  142. if has_seen_1 {
  143. assert_eq!(x, 2);
  144. } else {
  145. assert_eq!(x, 1);
  146. }
  147. }
  148. }
  149. });
  150. }