-
Notifications
You must be signed in to change notification settings - Fork 229
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This adds a new example on how to lift events from the synchronous code into async rust.
- Loading branch information
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}); | ||
} |