signals.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. use dioxus::prelude::*;
  2. use std::time::Duration;
  3. fn main() {
  4. launch_desktop(app);
  5. }
  6. fn app() -> Element {
  7. let mut running = use_signal(|| true);
  8. let mut count = use_signal(|| 0);
  9. let mut saved_values = use_signal(|| vec![0.to_string()]);
  10. // Signals can be used in async functions without an explicit clone since they're 'static and Copy
  11. // Signals are backed by a runtime that is designed to deeply integrate with Dioxus apps
  12. use_future(|| async move {
  13. loop {
  14. if running() {
  15. count += 1;
  16. }
  17. let val = running.read();
  18. tokio::time::sleep(Duration::from_millis(400)).await;
  19. println!("Running: {}", *val);
  20. }
  21. });
  22. rsx! {
  23. h1 { "High-Five counter: {count}" }
  24. button { onclick: move |_| count += 1, "Up high!" }
  25. button { onclick: move |_| count -= 1, "Down low!" }
  26. button { onclick: move |_| running.toggle(), "Toggle counter" }
  27. button { onclick: move |_| saved_values.push(count.cloned().to_string()), "Save this value" }
  28. button { onclick: move |_| saved_values.write().clear(), "Clear saved values" }
  29. // We can do boolean operations on the current signal value
  30. if count() > 5 {
  31. h2 { "High five!" }
  32. }
  33. // We can cleanly map signals with iterators
  34. for value in saved_values.read().iter() {
  35. h3 { "Saved value: {value}" }
  36. }
  37. // We can also use the signal value as a slice
  38. if let [ref first, .., ref last] = saved_values.read().as_slice() {
  39. li { "First and last: {first}, {last}" }
  40. } else {
  41. "No saved values"
  42. }
  43. }
  44. }