May 5, 2022

FileSystemWatcher Extensions

We can use extension classes to allow React to be used with other FileSystemWatcher usage cases:
public static class FileSystemWatcherExtender
{
  // Returns an IObservable, which is effectively a publisher
  // which can be subscribed to and disposed of when finished with
  public static IObservable<FileSystemEventArgs> 
    GetFileChangedPublisher(this FileSystemWatcher fileSystemWatcher)
  {
      Debug.Assert(fileSystemWatcher != null);
      var result = Observable
        .FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
            ev => fileSystemWatcher.Changed += ev,
            ev => fileSystemWatcher.Changed -= ev)
        .Select(ev => ev.EventArgs);
      return result;
  }

  // Use this to subscribe to FileSystemWatcher errors
  public static IObservable<ErrorEventArgs> 
    GetErrorPublisher(this FileSystemWatcher fileSystemWatcher)
  {
    Debug.Assert(fileSystemWatcher != null);
    return Observable
      .FromEventPattern<ErrorEventHandler, ErrorEventArgs>(
            ev => fileSystemWatcher.Error += ev,
            ev => fileSystemWatcher.Error -= ev)
      .Select(x => x.EventArgs);
  }
}
And to use it
FileSystemWatcher filesystemwatcher = BuildMyFileSystemWatcher();
...
// Subscribed to filesystem watcher changes
// where "onChanged" is a Func<FileSystemEventArgs>
IDisposable subscription = fileSystemWatcher.GetFileChangedPublisher().Subscribe(onChanged);   
...
subscription.Dispose(); // Finish with our subscription
...

No comments: