suspense.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::future::IntoFuture;
  2. use dioxus::prelude::*;
  3. #[inline_props]
  4. fn suspense_boundary<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
  5. cx.use_hook(|| cx.provide_context(SuspenseBoundary::new(cx.scope_id())));
  6. cx.render(rsx! { children })
  7. }
  8. fn basic_child(cx: Scope) -> Element {
  9. cx.render(rsx! {
  10. div { "basic child 1" }
  11. })
  12. }
  13. async fn async_child(cx: Scope<'_>) -> Element {
  14. let username = use_future!(cx, || async {
  15. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  16. "async child 1"
  17. });
  18. let age = use_future!(cx, || async {
  19. tokio::time::sleep(std::time::Duration::from_secs(2)).await;
  20. println!("long future completed");
  21. 1234
  22. });
  23. let (_user, _age) = use_future!(cx, || async {
  24. tokio::join!(
  25. tokio::time::sleep(std::time::Duration::from_secs(1)),
  26. tokio::time::sleep(std::time::Duration::from_secs(2))
  27. );
  28. ("async child 1", 1234)
  29. })
  30. .await;
  31. let (username, age) = tokio::join!(username.into_future(), age.into_future());
  32. cx.render(rsx!(
  33. div { "Hello! {username}, you are {age}, {_user} {_age}" }
  34. ))
  35. }
  36. #[tokio::test]
  37. async fn basic_prints() {
  38. let mut dom = VirtualDom::new(|cx| {
  39. cx.render(rsx! {
  40. div {
  41. h1 { "var" }
  42. suspense_boundary {
  43. basic_child { }
  44. async_child { }
  45. }
  46. }
  47. })
  48. });
  49. dbg!(dom.rebuild());
  50. dom.wait_for_work().await;
  51. dbg!(dom.rebuild());
  52. }