1
0

async.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 || {
  16. //
  17. async move {
  18. loop {
  19. TimeoutFuture::new(250).await;
  20. // *async_count.modify() += dir;
  21. }
  22. }
  23. });
  24. cx.render(rsx! {
  25. div {
  26. h1 {"count is {count}"}
  27. button { onclick: move |_| task.stop(),
  28. "Stop counting"
  29. }
  30. button { onclick: move |_| task.resume(),
  31. "Start counting"
  32. }
  33. button {
  34. onclick: move |_| {
  35. *direction.modify() *= -1;
  36. task.restart();
  37. },
  38. "Switch counting direcion"
  39. }
  40. }
  41. })
  42. }