async.rs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. fn main() {
  8. dioxus::desktop::launch(App, |c| c).unwrap();
  9. }
  10. pub static App: FC<()> = |cx, _| {
  11. let count = use_state(cx, || 0);
  12. let mut direction = use_state(cx, || 1);
  13. let (async_count, dir) = (count.for_async(), *direction);
  14. let (task, _) = use_task(cx, move || async move {
  15. loop {
  16. TimeoutFuture::new(250).await;
  17. *async_count.get_mut() += dir;
  18. }
  19. });
  20. rsx!(cx, div {
  21. h1 {"count is {count}"}
  22. button {
  23. "Stop counting"
  24. onclick: move |_| task.stop()
  25. }
  26. button {
  27. "Start counting"
  28. onclick: move |_| task.resume()
  29. }
  30. button {
  31. "Switch counting direcion"
  32. onclick: move |_| {
  33. direction *= -1;
  34. task.restart();
  35. }
  36. }
  37. })
  38. };