dioxus/examples/signals.rs

51 lines
1.6 KiB
Rust
Raw Normal View History

2023-01-02 00:57:33 +00:00
use dioxus::prelude::*;
use std::time::Duration;
fn main() {
launch_desktop(app);
2023-01-02 00:57:33 +00:00
}
fn app() -> Element {
let mut running = use_signal(|| true);
let mut count = use_signal(|| 0);
let mut saved_values = use_signal(|| vec![0.to_string()]);
2023-01-02 00:57:33 +00:00
// Signals can be used in async functions without an explicit clone since they're 'static and Copy
// Signals are backed by a runtime that is designed to deeply integrate with Dioxus apps
2024-01-14 05:12:21 +00:00
use_future(|| async move {
2023-01-02 00:57:33 +00:00
loop {
if running() {
2023-10-16 00:50:23 +00:00
count += 1;
}
2023-01-02 03:57:16 +00:00
tokio::time::sleep(Duration::from_millis(400)).await;
2023-01-02 00:57:33 +00:00
}
});
2024-01-16 19:18:46 +00:00
rsx! {
2023-01-02 00:57:33 +00:00
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
2023-10-16 00:52:01 +00:00
button { onclick: move |_| running.toggle(), "Toggle counter" }
2024-01-24 00:58:29 +00:00
button { onclick: move |_| saved_values.push(count().to_string()), "Save this value" }
2023-10-17 22:52:13 +00:00
button { onclick: move |_| saved_values.write().clear(), "Clear saved values" }
2023-01-02 03:57:16 +00:00
// We can do boolean operations on the current signal value
if count() > 5 {
h2 { "High five!" }
2023-01-02 03:57:16 +00:00
}
// We can cleanly map signals with iterators
for value in saved_values.read().iter() {
h3 { "Saved value: {value}" }
}
// We can also use the signal value as a slice
2023-10-17 23:06:43 +00:00
if let [ref first, .., ref last] = saved_values.read().as_slice() {
li { "First and last: {first}, {last}" }
} else {
"No saved values"
}
2024-01-14 05:12:21 +00:00
}
2023-01-02 00:57:33 +00:00
}