Replies: 1 comment 2 replies
-
If you're still hitting issues with this, you have two options that could work: You could use BroadcastStream to wrap the You could also do something like the following, using async-stream: use std::convert::Infallible;
use async_stream::try_stream;
use axum::extract::State;
use axum::routing::get;
use axum::response::sse::{Event, KeepAlive, Sse};
use futures::Stream;
use my_crate::ServerState;
async fn event_stream(
State(state): State<ServerState>
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let mut receiver = state.event_stream.subscribe();
Sse::new(try_stream! {
loop {
match receiver.recv().await {
Ok(i) => {
let event = Event::default()
.data(i);
yield event;
},
Err(e) => {
tracing::error!(error = ?e, "Failed to get");
}
}
}
}).keep_alive(KeepAlive::default())
} In this case my |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I want to serve connected clients server side events when a condition on my server is met.
I know you can use web sockets for this (like in the chat app) but my front end is already written and I am currently trying to port my back-end.
So I have set up my route as shown in the example. I am trying to figure out how I can trigger the
stream
on my own condition but could not make it work yet. Can somebody help me?My route has access to a
tokio::sync::broadcast::Receiver<T>
. I would like toawait
thereceive
method of this receiver and send out a new event every time I get a new message.I tried to write the logic in the
.data()
call, but it will only let me write synchronous code there.(says that the .
repeat_with()
call needs to beasync
but it is not.Beta Was this translation helpful? Give feedback.
All reactions