Watch Files with Debounced Events
Receive filesystem notifications through notify, keep the watcher alive with a handle, and collapse rapid events into one batch.
Code
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
use std::sync::mpsc::{channel, Receiver};
use std::time::{Duration, Instant};
struct WatchHandle {
_watcher: RecommendedWatcher,
events: Receiver<Event>,
}
fn watch(path: &Path) -> notify::Result<WatchHandle> {
let (sender, events) = channel();
let mut watcher = RecommendedWatcher::new(
move |result: notify::Result<Event>| {
if let Ok(event) = result {
let _ = sender.send(event);
}
},
Config::default(),
)?;
watcher.watch(path, RecursiveMode::Recursive)?;
Ok(WatchHandle {
_watcher: watcher,
events,
})
}
fn main() -> notify::Result<()> {
let handle = watch(Path::new("."))?;
let started = Instant::now();
let mut last = Instant::now();
let mut pending = false;
let mut count = 0;
loop {
match handle.events.recv_timeout(Duration::from_millis(200)) {
Ok(event) => {
last = Instant::now();
pending = true;
count += 1;
println!("raw event: {:?}", event.kind);
}
Err(_) if pending && last.elapsed() >= Duration::from_millis(500) => {
println!("debounced batch of {count} events ready");
break;
}
Err(_) if !pending && started.elapsed() >= Duration::from_secs(2) => {
println!("no changes observed");
break;
}
Err(_) => {}
}
}
Ok(())
}
What the code does
The working surface is the functions watch and main — everything else is wiring.
Result is the error channel: the caller receives the failure as a value instead of an exception. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
Points of care
- Plan for an install step:
notify::is a real dependency, resolved by the package manager. Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Using it
Signature: fn watch(path: &Path) -> notify::Result<WatchHandle>
The demo output is labeled (raw event:, debounced batch of, no changes observed), so every printed line maps back to its originating operation.
Launch the file; main takes over and steps through watch.
Key statements
Err(_) if pending && last.elapsed() >= Duration::from_millis(500) => {
println!("debounced batch of {count} events ready");
break;
}
Err(_) if !pending && started.elapsed() >= Duration::from_secs(2) => {
println!("no changes observed");
break;
}
Ok(event) => {
last = Instant::now();
pending = true;
count += 1;
println!("raw event: {:?}", event.kind);
}
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What is the error handling style?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does this need from the package registry?
- These are real dependencies: `notify::`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.