Skip to content

Commit

Permalink
Add async example
Browse files Browse the repository at this point in the history
This adds a new example on how to lift events from the synchronous code
into async rust.
  • Loading branch information
erickt committed Jun 8, 2021
1 parent 4f410f3 commit dca87cb
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ fsevent-sys = "4"
winapi = { version = "0.3.8", features = ["fileapi", "handleapi", "ioapiset", "minwinbase", "synchapi", "winbase", "winnt"] }

[dev-dependencies]
futures = "0.3"
serde_json = "1.0.39"
tempfile = "3.2.0"

Expand Down
47 changes: 47 additions & 0 deletions examples/async_monitor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use notify::{RecommendedWatcher, RecursiveMode, Event, Watcher};
use std::path::Path;
use futures::{SinkExt, StreamExt, channel::mpsc::{channel, Receiver}};

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 = Watcher::new_immediate(move |res| {
futures::executor::block_on(async {
tx.send(res).await.unwrap();
})
})?;

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, RecursiveMode::Recursive)?;

while let Some(res) = rx.next().await {
match res {
Ok(event) => println!("changed: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}

Ok(())
}

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)
}
});
}

0 comments on commit dca87cb

Please sign in to comment.