future.rs 983 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //! A simple example that shows how to use the use_future hook to run a background task.
  2. //!
  3. //! use_future assumes your future will never complete - it won't return a value.
  4. //! If you want to return a value, use use_resource instead.
  5. use dioxus::prelude::*;
  6. use std::time::Duration;
  7. fn main() {
  8. launch_desktop(app);
  9. }
  10. fn app() -> Element {
  11. let mut count = use_signal(|| 0);
  12. // use_future will run the future
  13. use_future(move || async move {
  14. loop {
  15. tokio::time::sleep(Duration::from_millis(200)).await;
  16. count += 1;
  17. }
  18. });
  19. // We can also spawn futures from effects, handlers, or other futures
  20. use_effect(move || {
  21. spawn(async move {
  22. tokio::time::sleep(Duration::from_secs(5)).await;
  23. count.set(100);
  24. });
  25. });
  26. rsx! {
  27. div {
  28. h1 { "Current count: {count}" }
  29. button { onclick: move |_| count.set(0), "Reset the count" }
  30. }
  31. }
  32. }