signals.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // We can do early returns and conditional rendering which will pause all futures that haven't been polled
  16. if count() > 30 {
  17. return rsx! {
  18. h1 { "Count is too high!" }
  19. button {
  20. onclick: move |_| count.set(0),
  21. "Press to reset"
  22. }
  23. };
  24. }
  25. // use_future will spawn an infinitely running future that can be started and stopped
  26. use_future(|| async move {
  27. loop {
  28. if running() {
  29. count += 1;
  30. }
  31. tokio::time::sleep(Duration::from_millis(400)).await;
  32. }
  33. });
  34. // use_resource will spawn a future that resolves to a value - essentially an async memo
  35. let slow_count = use_resource(move || async move {
  36. tokio::time::sleep(Duration::from_millis(200)).await;
  37. count() * 2
  38. });
  39. rsx! {
  40. h1 { "High-Five counter: {count}" }
  41. button { onclick: move |_| count += 1, "Up high!" }
  42. button { onclick: move |_| count -= 1, "Down low!" }
  43. button { onclick: move |_| running.toggle(), "Toggle counter" }
  44. button { onclick: move |_| saved_values.push(count().to_string()), "Save this value" }
  45. button { onclick: move |_| saved_values.clear(), "Clear saved values" }
  46. // We can do boolean operations on the current signal value
  47. if count() > 5 {
  48. h2 { "High five!" }
  49. }
  50. // We can cleanly map signals with iterators
  51. for value in saved_values.iter() {
  52. h3 { "Saved value: {value}" }
  53. }
  54. // We can also use the signal value as a slice
  55. if let [ref first, .., ref last] = saved_values.read().as_slice() {
  56. li { "First and last: {first}, {last}" }
  57. } else {
  58. "No saved values"
  59. }
  60. // You can pass a value directly to any prop that accepts a signal
  61. Child { count: doubled_count() }
  62. }
  63. }
  64. #[component]
  65. fn Child(mut count: ReadOnlySignal<i32>) -> Element {
  66. rsx! {
  67. h1 { "{count}" }
  68. }
  69. }