thisweek_core/
notify.rs

1use core::time::Duration;
2use notify_debouncer_mini::{new_debouncer, notify::*, DebounceEventResult};
3use std::path::Path;
4
5type Callback = fn();
6
7pub struct Notify {
8    pub debouncer: notify_debouncer_mini::Debouncer<RecommendedWatcher>,
9}
10
11impl Notify {
12    pub fn new(path: &Path, callback: Callback) -> Self {
13        // Select recommended watcher for debouncer.
14        // Using a callback here, could also be a channel.
15        let mut debouncer = new_debouncer(
16            Duration::from_millis(500),
17            move |res: DebounceEventResult| match res {
18                Ok(events) => {
19                    events
20                        .iter()
21                        .for_each(|e| println!("Event {:?} for {:?}", e.kind, e.path));
22                    (callback)();
23                }
24                Err(e) => println!("Error {:?}", e),
25            },
26        )
27        .unwrap();
28
29        // Add a path to be watched. All files and directories at that path and
30        // below will be monitored for changes.
31        // println!("watching {path}");
32        debouncer
33            .watcher()
34            .watch(path, RecursiveMode::Recursive)
35            .unwrap();
36
37        Notify { debouncer }
38    }
39    // note that dropping the debouncer (as will happen here) also ends the debouncer
40    // thus this demo would need an endless loop to keep running
41}