dioxus/examples/signals.rs

72 lines
2.3 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
2024-01-24 23:53:39 +00:00
// use_memo will recompute the value of the signal whenever the captured signals change
let doubled_count = use_memo(move || count() * 2);
// use_effect will subscribe to any changes in the signal values it captures
// effects will always run after first mount and then whenever the signal values change
use_effect(move || println!("Count changed to {}", count()));
// use_future will spawn an infinitely running future that can be started and stopped
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-24 23:53:39 +00:00
// use_resource will spawn a future that resolves to a value - essentially an async memo
let slow_count = use_resource(move || async move {
tokio::time::sleep(Duration::from_millis(200)).await;
count() * 2
});
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" }
2024-01-27 06:33:41 +00:00
button { onclick: move |_| saved_values.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
2024-01-27 06:33:41 +00:00
for value in saved_values.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-29 19:36:39 +00:00
// You can pass a value directly to any prop that accepts a signal
2024-01-29 21:57:23 +00:00
Child { count: doubled_count() }
2024-01-29 19:36:39 +00:00
}
}
#[component]
2024-01-29 21:57:23 +00:00
fn Child(mut count: ReadOnlySignal<i32>) -> Element {
2024-01-29 19:36:39 +00:00
rsx! {
h1 { "{count}" }
2024-01-14 05:12:21 +00:00
}
2023-01-02 00:57:33 +00:00
}