forked from notify-rs/notify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
async_monitor.rs
54 lines (45 loc) · 1.52 KB
/
async_monitor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use futures::{
channel::mpsc::{channel, Receiver},
SinkExt, StreamExt,
};
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
/// Async, futures channel based event watching
fn main() {
let path = std::env::args()
.nth(1)
.expect("Argument 1 needs to be a path");
println!("watching {}", path);
futures::executor::block_on(async {
if let Err(e) = async_watch(path).await {
println!("error: {:?}", e)
}
});
}
fn async_watcher() -> notify::Result<(RecommendedWatcher, Receiver<notify::Result<Event>>)> {
let (mut tx, rx) = channel(1);
// Automatically select the best implementation for your platform.
// You can also access each implementation directly e.g. INotifyWatcher.
let watcher = RecommendedWatcher::new(
move |res| {
futures::executor::block_on(async {
tx.send(res).await.unwrap();
})
},
Config::default(),
)?;
Ok((watcher, rx))
}
async fn async_watch<P: AsRef<Path>>(path: P) -> notify::Result<()> {
let (mut watcher, mut rx) = async_watcher()?;
// Add a path to be watched. All files and directories at that path and
// below will be monitored for changes.
watcher.watch(path.as_ref(), RecursiveMode::Recursive)?;
while let Some(res) = rx.next().await {
match res {
Ok(event) => println!("changed: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}
Ok(())
}