streams.rs 963 B

12345678910111213141516171819202122232425262728293031323334353637
  1. //! Handle async streams using use_future and awaiting the next value.
  2. use async_std::task::sleep;
  3. use dioxus::prelude::*;
  4. use futures_util::{future, stream, Stream, StreamExt};
  5. fn main() {
  6. dioxus::launch(app);
  7. }
  8. fn app() -> Element {
  9. let mut count = use_signal(|| 10);
  10. use_future(move || async move {
  11. // Create the stream.
  12. // This could be a network request, a file read, or any other async operation.
  13. let mut stream = some_stream();
  14. // Await the next value from the stream.
  15. while let Some(second) = stream.next().await {
  16. count.set(second);
  17. }
  18. });
  19. rsx! {
  20. h1 { "High-Five counter: {count}" }
  21. }
  22. }
  23. fn some_stream() -> std::pin::Pin<Box<dyn Stream<Item = i32>>> {
  24. Box::pin(
  25. stream::once(future::ready(0)).chain(stream::iter(1..).then(|second| async move {
  26. sleep(std::time::Duration::from_secs(1)).await;
  27. second
  28. })),
  29. )
  30. }