main.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use dioxus::prelude::*;
  2. use futures::StreamExt;
  3. use server_fn::codec::{StreamingText, TextStream};
  4. fn app() -> Element {
  5. let mut response = use_signal(String::new);
  6. rsx! {
  7. button {
  8. onclick: move |_| async move {
  9. response.write().clear();
  10. if let Ok(stream) = test_stream().await {
  11. response.write().push_str("Stream started\n");
  12. let mut stream = stream.into_inner();
  13. while let Some(Ok(text)) = stream.next().await {
  14. response.write().push_str(&text);
  15. }
  16. }
  17. },
  18. "Start stream"
  19. }
  20. "{response}"
  21. }
  22. }
  23. #[server(output = StreamingText)]
  24. pub async fn test_stream() -> Result<TextStream, ServerFnError> {
  25. let (tx, rx) = futures::channel::mpsc::unbounded();
  26. tokio::spawn(async move {
  27. loop {
  28. tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
  29. let _ = tx.unbounded_send(Ok("Hello, world!".to_string()));
  30. }
  31. });
  32. Ok(TextStream::new(rx))
  33. }
  34. fn main() {
  35. launch(app)
  36. }