dioxus/examples/streams.rs

38 lines
962 B
Rust
Raw Normal View History

//! Handle async streams using use_future and awaiting the next value.
2024-01-08 19:25:20 +00:00
use dioxus::prelude::*;
use futures_util::{future, stream, Stream, StreamExt};
use std::time::Duration;
fn main() {
launch_desktop(app);
2024-01-08 19:25:20 +00:00
}
fn app() -> Element {
let mut count = use_signal(|| 10);
2024-01-08 19:25:20 +00:00
use_future(move || async move {
// Create the stream.
// This could be a network request, a file read, or any other async operation.
2024-01-08 19:25:20 +00:00
let mut stream = some_stream();
// Await the next value from the stream.
2024-01-08 19:25:20 +00:00
while let Some(second) = stream.next().await {
count.set(second);
}
});
2024-01-16 19:18:46 +00:00
rsx! {
2024-01-08 19:25:20 +00:00
h1 { "High-Five counter: {count}" }
2024-01-14 05:12:21 +00:00
}
2024-01-08 19:25:20 +00:00
}
fn some_stream() -> std::pin::Pin<Box<dyn Stream<Item = i32>>> {
Box::pin(
stream::once(future::ready(0)).chain(stream::iter(1..).then(|second| async move {
tokio::time::sleep(Duration::from_secs(1)).await;
second
})),
)
}