notify-rs / notify

🔭 Cross-platform filesystem notification library for Rust.
https://docs.rs/notify
2.77k stars 222 forks source link

Advice for multiple watchers of the same path(s) #542

Closed NuSkooler closed 1 year ago

NuSkooler commented 1 year ago

This is not a bug, but more of a question. I hope this is the right place, I didn't see a "Discussions" area.

I'm looking for implementation advice for a system in which 1:N paths, of which some could overlap, can be implemented along with multiple receiver channels. I think there are a lot of ways to go about this, but it seemed appropriate to ask here. What I don't want to do is create something that wastes resources.

What I'm after is something like this:'

struct Monitor {}
...
impl Monitor {
  pub fn subscribe(path: &Path, receiver: Receiver<Event>) {
   ...
  }
}

Where I have a single "global" monitor, and multiple components -- from different Tokio thread/tasks can subscribe to watch a particular path.

My thought was a new() on Monitor that creates the watcher, and a start() function that spawns a consumer task, then dispatches to the "subscribers" via a HashMap of path:channels.

Is there a better way?

0xpr03 commented 1 year ago

No I think your approach is the correct one: Create some pub-sub system where you distribute the events to your subscribers, such that you only need one notify instance.

You could also run notify with the crossbeam feature and thus allow multiple listeners - problem is then each of your subscribers has to filter for it. Which may be worse in performance and maintainability than one instance handling this and obviously creates n times the work/memory/.. for n listeners, regardless of whether they need it.

NuSkooler commented 1 year ago

@0xpr03 Thank you so much for your response, very much appreciated! I will continue down this path... Wanted to make sure I wasn't missing something!