signals.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. use dioxus::prelude::*;
  2. use std::time::Duration;
  3. fn main() {
  4. dioxus_desktop::launch(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. tokio::time::sleep(Duration::from_millis(400)).await;
  18. }
  19. });
  20. rsx! {
  21. h1 { "High-Five counter: {count}" }
  22. button { onclick: move |_| count += 1, "Up high!" }
  23. button { onclick: move |_| count -= 1, "Down low!" }
  24. button { onclick: move |_| running.toggle(), "Toggle counter" }
  25. button { onclick: move |_| saved_values.push(count.cloned().to_string()), "Save this value" }
  26. button { onclick: move |_| saved_values.write().clear(), "Clear saved values" }
  27. // We can do boolean operations on the current signal value
  28. if count() > 5 {
  29. h2 { "High five!" }
  30. }
  31. // We can cleanly map signals with iterators
  32. for value in saved_values.read().iter() {
  33. h3 { "Saved value: {value}" }
  34. }
  35. // We can also use the signal value as a slice
  36. if let [ref first, .., ref last] = saved_values.read().as_slice() {
  37. li { "First and last: {first}, {last}" }
  38. } else {
  39. "No saved values"
  40. }
  41. }
  42. }