Spaces:
Build error
Build error
Update src/sse/stream.rs
Browse files- src/sse/stream.rs +18 -0
src/sse/stream.rs
CHANGED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use axum::{extract::State, response::sse::{Event, Sse}};
|
| 2 |
+
use futures_util::stream::Stream;
|
| 3 |
+
use std::{convert::Infallible, sync::Arc};
|
| 4 |
+
use tokio_stream::{wrappers::BroadcastStream, StreamExt};
|
| 5 |
+
use crate::AppState;
|
| 6 |
+
|
| 7 |
+
pub async fn sse_handler(
|
| 8 |
+
State(state): State<Arc<AppState>>,
|
| 9 |
+
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
| 10 |
+
let rx = state.tx.subscribe();
|
| 11 |
+
let stream = BroadcastStream::new(rx).map(|msg| {
|
| 12 |
+
match msg {
|
| 13 |
+
Ok(data) => Ok(Event::default().data(data)),
|
| 14 |
+
Err(_) => Ok(Event::default().data("error")),
|
| 15 |
+
}
|
| 16 |
+
});
|
| 17 |
+
Sse::new(stream)
|
| 18 |
+
}
|