dioxus/packages/signals/examples/split_subscriptions.rs

108 lines
2.4 KiB
Rust
Raw Normal View History

2023-08-08 01:20:03 +00:00
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_signals::Signal;
fn main() {
// dioxus_desktop::launch(app);
2023-08-08 01:20:03 +00:00
}
#[derive(Clone, Copy, Default)]
struct ApplicationData {
first_data: Signal<i32>,
second_data: Signal<i32>,
many_signals: Signal<Vec<Signal<i32>>>,
}
fn app() -> Element {
use_context_provider(ApplicationData::default);
2023-08-08 01:20:03 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
div { ReadsFirst {} }
div { ReadsSecond {} }
div { ReadsManySignals {} }
2023-08-08 01:20:03 +00:00
}
}
#[component]
fn ReadsFirst() -> Element {
2023-08-08 01:20:03 +00:00
println!("running first");
let mut data = use_context::<ApplicationData>();
2023-08-08 01:20:03 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
2023-08-08 01:20:03 +00:00
button {
onclick: move |_| {
*data.first_data.write() += 1;
},
"Increase"
}
button {
onclick: move |_| {
*data.first_data.write() -= 1;
},
"Decrease"
}
button {
onclick: move |_| {
*data.first_data.write() = 0;
},
"Reset"
}
"{data.first_data}"
}
}
#[component]
fn ReadsSecond() -> Element {
2023-08-08 01:20:03 +00:00
println!("running second");
let mut data = use_context::<ApplicationData>();
2023-08-08 01:20:03 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
button { onclick: move |_| data.second_data += 1, "Increase" }
button { onclick: move |_| data.second_data -= 1, "Decrease" }
button { onclick: move |_| data.second_data.set(0), "Reset" }
2023-08-08 01:20:03 +00:00
"{data.second_data}"
}
}
#[component]
fn ReadsManySignals() -> Element {
2023-08-08 01:20:03 +00:00
println!("running many signals");
let mut data = use_context::<ApplicationData>();
2023-08-08 01:20:03 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
2023-08-08 01:20:03 +00:00
button {
onclick: move |_| data.many_signals.write().push(Signal::new(0)),
2023-08-08 01:20:03 +00:00
"Create"
}
button {
onclick: move |_| { data.many_signals.write().pop(); },
2023-08-08 01:20:03 +00:00
"Destroy"
}
button {
onclick: move |_| {
if let Some(mut first) = data.many_signals.read().first().cloned() {
first += 1;
2023-08-08 01:20:03 +00:00
}
},
"Increase First Item"
}
for signal in data.many_signals {
2023-12-23 19:57:49 +00:00
Child { count: *signal }
2023-08-08 01:20:03 +00:00
}
}
}
#[component]
fn Child(mut count: Signal<i32>) -> Element {
2023-08-08 01:20:03 +00:00
println!("running child");
2024-01-16 19:18:46 +00:00
rsx! {
2023-08-08 01:20:03 +00:00
div {
"Child: {count}"
button { onclick: move |_| count += 1, "Increase" }
button { onclick: move |_| count -= 1, "Decrease" }
2023-08-08 01:20:03 +00:00
}
}
}