1
0

backgrounded_futures.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //! Backgrounded futures example
  2. //!
  3. //! This showcases how use_future, use_memo, and use_effect will stop running if the component returns early.
  4. //! Generally you should avoid using early returns around hooks since most hooks are not properly designed to
  5. //! handle early returns. However, use_future *does* pause the future when the component returns early, and so
  6. //! hooks that build on top of it like use_memo and use_effect will also pause.
  7. //!
  8. //! This example is more of a demonstration of the behavior than a practical use case, but it's still interesting to see.
  9. use dioxus::prelude::*;
  10. fn main() {
  11. launch_desktop(app);
  12. }
  13. fn app() -> Element {
  14. let mut show_child = use_signal(|| true);
  15. let mut count = use_signal(|| 0);
  16. let child = use_memo(move || {
  17. rsx! {
  18. Child { count }
  19. }
  20. });
  21. rsx! {
  22. // Some toggle/controls to show the child or increment the count
  23. button { onclick: move |_| show_child.toggle(), "Toggle child" }
  24. button { onclick: move |_| count += 1, "Increment count" }
  25. if show_child() {
  26. {child()}
  27. }
  28. }
  29. }
  30. #[component]
  31. fn Child(count: Signal<i32>) -> Element {
  32. let mut early_return = use_signal(|| false);
  33. let early = rsx! {
  34. button { onclick: move |_| early_return.toggle(), "Toggle {early_return} early return" }
  35. };
  36. if early_return() {
  37. return early;
  38. }
  39. use_future(move || async move {
  40. loop {
  41. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  42. println!("Child")
  43. }
  44. });
  45. use_effect(move || println!("Child count: {}", count()));
  46. rsx! {
  47. div {
  48. "Child component"
  49. {early}
  50. }
  51. }
  52. }