task.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
  2. use dioxus::prelude::*;
  3. use std::{sync::atomic::AtomicUsize, time::Duration};
  4. static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
  5. #[tokio::test]
  6. async fn it_works() {
  7. let mut dom = VirtualDom::new(app);
  8. let _ = dom.rebuild();
  9. tokio::select! {
  10. _ = dom.wait_for_work() => {}
  11. _ = tokio::time::sleep(Duration::from_millis(500)) => {}
  12. };
  13. // By the time the tasks are finished, we should've accumulated ticks from two tasks
  14. // Be warned that by setting the delay to too short, tokio might not schedule in the tasks
  15. assert_eq!(
  16. POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed),
  17. 135
  18. );
  19. }
  20. fn app(cx: Scope) -> Element {
  21. cx.use_hook(|| {
  22. cx.spawn(async {
  23. for x in 0..10 {
  24. tokio::time::sleep(Duration::from_micros(50)).await;
  25. POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
  26. }
  27. });
  28. cx.spawn(async {
  29. for x in 0..10 {
  30. tokio::time::sleep(Duration::from_micros(25)).await;
  31. POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
  32. }
  33. });
  34. });
  35. cx.render(rsx!(()))
  36. }