signals.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // use_memo will recompute the value of the signal whenever the captured signals change
  11. let doubled_count = use_memo(move || count() * 2);
  12. // use_effect will subscribe to any changes in the signal values it captures
  13. // effects will always run after first mount and then whenever the signal values change
  14. use_effect(move || println!("Count changed to {}", count()));
  15. // use_future will spawn an infinitely running future that can be started and stopped
  16. use_future(|| async move {
  17. loop {
  18. if running() {
  19. count += 1;
  20. }
  21. tokio::time::sleep(Duration::from_millis(400)).await;
  22. }
  23. });
  24. // use_resource will spawn a future that resolves to a value - essentially an async memo
  25. let slow_count = use_resource(move || async move {
  26. tokio::time::sleep(Duration::from_millis(200)).await;
  27. count() * 2
  28. });
  29. rsx! {
  30. h1 { "High-Five counter: {count}" }
  31. button { onclick: move |_| count += 1, "Up high!" }
  32. button { onclick: move |_| count -= 1, "Down low!" }
  33. button { onclick: move |_| running.toggle(), "Toggle counter" }
  34. button { onclick: move |_| saved_values.push(count().to_string()), "Save this value" }
  35. button { onclick: move |_| saved_values.clear(), "Clear saved values" }
  36. // We can do boolean operations on the current signal value
  37. if count() > 5 {
  38. h2 { "High five!" }
  39. }
  40. // We can cleanly map signals with iterators
  41. for value in saved_values.iter() {
  42. h3 { "Saved value: {value}" }
  43. }
  44. // We can also use the signal value as a slice
  45. if let [ref first, .., ref last] = saved_values.read().as_slice() {
  46. li { "First and last: {first}, {last}" }
  47. } else {
  48. "No saved values"
  49. }
  50. // You can pass a value directly to any prop that accepts a signal
  51. Child { count: 0 }
  52. }
  53. }
  54. #[component]
  55. fn Child(mut count: Signal<i32>) -> Element {
  56. rsx! {
  57. h1 { "{count}" }
  58. button { onclick: move |_| count += 1, "Up high!" }
  59. button { onclick: move |_| count -= 1, "Down low!" }
  60. }
  61. }