dioxus/examples/async.rs

45 lines
1 KiB
Rust
Raw Normal View History

2021-09-24 04:05:56 +00:00
/*
This example shows how to use async and loops to implement a coroutine in a component. Coroutines can be controlled via
the `TaskHandle` object.
*/
2021-07-09 03:25:27 +00:00
use dioxus::prelude::*;
2021-09-24 04:05:56 +00:00
use gloo_timers::future::TimeoutFuture;
2021-07-09 03:25:27 +00:00
fn main() {
2021-09-24 04:05:56 +00:00
dioxus::desktop::launch(App, |c| c).unwrap();
2021-07-09 03:25:27 +00:00
}
2021-09-24 04:05:56 +00:00
pub static App: FC<()> = |cx, _| {
2021-07-18 07:54:42 +00:00
let count = use_state(cx, || 0);
let mut direction = use_state(cx, || 1);
2021-07-09 03:25:27 +00:00
2021-07-18 07:54:42 +00:00
let (async_count, dir) = (count.for_async(), *direction);
2021-09-24 04:05:56 +00:00
let (task, _) = use_task(cx, move || async move {
2021-07-15 03:18:02 +00:00
loop {
2021-09-24 04:05:56 +00:00
TimeoutFuture::new(250).await;
2021-07-18 07:54:42 +00:00
*async_count.get_mut() += dir;
2021-07-15 03:18:02 +00:00
}
});
2021-07-09 03:25:27 +00:00
2021-09-24 04:05:56 +00:00
rsx!(cx, div {
h1 {"count is {count}"}
button {
"Stop counting"
onclick: move |_| task.stop()
}
button {
"Start counting"
onclick: move |_| task.resume()
}
button {
"Switch counting direcion"
onclick: move |_| {
direction *= -1;
task.restart();
2021-07-18 07:54:42 +00:00
}
2021-07-09 16:47:41 +00:00
}
})
};