-
Hi I want to use https://github.com/notify-rs/notify for file change notifications and use Axum Server Sent Events for communicating with client. Now how to send file change notification via SSE? Here is my pseudo code. use axum::{
Router,
routing::get,
response::sse::{Event, KeepAlive, Sse},
};
use std::{time::Duration, convert::Infallible, path::Path};
use tokio_stream::StreamExt as _ ;
use futures_util::stream::{self, Stream};
use notify::{Watcher, RecommendedWatcher, RecursiveMode, Result as NResult};
#[tokio::main]
async fn main() {
// file change notification code
fn event_fn(res: NResult<notify::Event>) {
match res {
// How to pass this event information to SSE handler?
Ok(event) => println!("event: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}
let mut watcher = notify::recommended_watcher(event_fn)?;
watcher.watch(Path::new("."), RecursiveMode::Recursive)?;
// build our application with a single route
let app = Router::new().route("/sse", get(sse_handler));
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
// A `Stream` that repeats an event every second
let stream = stream::repeat_with(|| Event::default().data("hi!"))
.map(Ok)
.throttle(Duration::from_secs(1));
Sse::new(stream).keep_alive(KeepAlive::default())
// how to send file change notifications based on events rather than time?
} Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Send on a channel |
Beta Was this translation helpful? Give feedback.
-
Thanks for this thread. Was off lost in compilation errors trying to coerce my Receiver into a Stream, didn't know about BroadcastStream. |
Beta Was this translation helpful? Give feedback.
Thanks. My working example.