async.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //! Example: README.md showcase
  2. //!
  3. //! The example from the README.md
  4. use dioxus::prelude::*;
  5. fn main() {
  6. dioxus::desktop::launch(App, |c| c).expect("faield to launch");
  7. }
  8. pub static App: FC<()> = |cx, props| {
  9. let count = use_state(cx, || 0);
  10. let mut direction = use_state(cx, || 1);
  11. let (async_count, dir) = (count.for_async(), *direction);
  12. let (task, _result) = use_task(cx, move || async move {
  13. loop {
  14. gloo_timers::future::TimeoutFuture::new(250).await;
  15. *async_count.get_mut() += dir;
  16. }
  17. });
  18. cx.render(rsx! {
  19. div {
  20. h1 {"count is {count}"}
  21. button {
  22. "Stop counting"
  23. onclick: move |_| task.stop()
  24. }
  25. button {
  26. "Start counting"
  27. onclick: move |_| task.resume()
  28. }
  29. button {
  30. "Switch counting direcion"
  31. onclick: move |_| {
  32. direction *= -1;
  33. task.restart();
  34. }
  35. }
  36. }
  37. })
  38. };