1
0

future.rs 968 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //! A simple example that shows how to use the use_future hook to run a background task.
  2. //!
  3. //! use_future won't return a value, analogous to use_effect.
  4. //! If you want to return a value from a future, use use_resource instead.
  5. use async_std::task::sleep;
  6. use dioxus::prelude::*;
  7. fn main() {
  8. launch(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. sleep(std::time::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. sleep(std::time::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. }