async.rs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. This example shows how to use async and loops to implement a coroutine in a component. Coroutines can be controlled via
  3. the `TaskHandle` object.
  4. */
  5. use dioxus::prelude::*;
  6. use gloo_timers::future::TimeoutFuture;
  7. #[tokio::main]
  8. async fn main() {
  9. dioxus::desktop::launch(app);
  10. }
  11. fn app(cx: Scope) -> Element {
  12. let count = use_state(&cx, || 0);
  13. let direction = use_state(&cx, || 1);
  14. let (async_count, dir) = (count.for_async(), *direction);
  15. let task = use_coroutine(&cx, move || async move {
  16. loop {
  17. TimeoutFuture::new(250).await;
  18. *async_count.modify() += dir;
  19. }
  20. });
  21. rsx!(cx, div {
  22. h1 {"count is {count}"}
  23. button { onclick: move |_| task.stop(),
  24. "Stop counting"
  25. }
  26. button { onclick: move |_| task.resume(),
  27. "Start counting"
  28. }
  29. button {
  30. onclick: move |_| {
  31. *direction.modify() *= -1;
  32. task.restart();
  33. },
  34. "Switch counting direcion"
  35. }
  36. })
  37. }