dioxus/examples/backgrounded_futures.rs

66 lines
1.7 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! Backgrounded futures example
//!
//! This showcases how use_future, use_memo, and use_effect will stop running if the component returns early.
//! Generally you should avoid using early returns around hooks since most hooks are not properly designed to
//! handle early returns. However, use_future *does* pause the future when the component returns early, and so
//! hooks that build on top of it like use_memo and use_effect will also pause.
//!
//! This example is more of a demonstration of the behavior than a practical use case, but it's still interesting to see.
use async_std::task::sleep;
2024-01-27 07:05:40 +00:00
use dioxus::prelude::*;
fn main() {
launch(app);
2024-01-27 07:05:40 +00:00
}
fn app() -> Element {
let mut show_child = use_signal(|| true);
let mut count = use_signal(|| 0);
let child = use_memo(move || {
rsx! {
2024-02-14 20:33:07 +00:00
Child { count }
2024-01-27 07:05:40 +00:00
}
});
rsx! {
2024-02-14 20:33:07 +00:00
// Some toggle/controls to show the child or increment the count
2024-01-27 07:05:40 +00:00
button { onclick: move |_| show_child.toggle(), "Toggle child" }
button { onclick: move |_| count += 1, "Increment count" }
2024-02-14 20:33:07 +00:00
2024-01-27 07:05:40 +00:00
if show_child() {
2024-02-14 20:33:07 +00:00
{child()}
2024-01-27 07:05:40 +00:00
}
}
}
#[component]
fn Child(count: Signal<i32>) -> Element {
let mut early_return = use_signal(|| false);
let early = rsx! {
button { onclick: move |_| early_return.toggle(), "Toggle {early_return} early return" }
};
if early_return() {
return early;
}
use_future(move || async move {
loop {
sleep(std::time::Duration::from_millis(100)).await;
2024-01-27 07:05:40 +00:00
println!("Child")
}
});
2024-02-14 20:33:07 +00:00
use_effect(move || println!("Child count: {}", count()));
2024-01-27 07:05:40 +00:00
rsx! {
2024-02-14 20:33:07 +00:00
div {
"Child component"
{early}
}
2024-01-27 07:05:40 +00:00
}
}