Skip to content

Instantly share code, notes, and snippets.

@tintoy
Created January 19, 2018 09:03
Show Gist options
  • Save tintoy/fbc565547e9a2da259cafe6ff1a96bda to your computer and use it in GitHub Desktop.
Save tintoy/fbc565547e9a2da259cafe6ff1a96bda to your computer and use it in GitHub Desktop.
IObservable for file-change notifications
using System;
using System.IO;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
/// <summary>
/// Extension methods for System.IO types.
/// </summary>
public static class IOExtensions
{
/// <summary>
/// Observe any changes relating to a file.
/// </summary>
/// <param name="file">
/// The target file.
/// </param>
/// <param name="notificationFilters">
/// <see cref="NotifyFilters"/> indicating which types of notifications should be observed.
/// </param>
/// <returns>
/// An <see cref="IObservable{T}"/> sequence of <see cref="WatcherChangeTypes"/> values.
/// </returns>
public static IObservable<WatcherChangeTypes> ObserveChanges(this FileInfo file, NotifyFilters notificationFilters = NotifyFilters.Size)
{
return Observable.Create<WatcherChangeTypes>(subscriber =>
{
var disposal = new CompositeDisposable();
var watcher = new FileSystemWatcher(file.DirectoryName)
{
Filter = file.Name,
IncludeSubdirectories = false,
NotifyFilter = NotifyFilters.Size // Only react when data is appended.
};
watcher.Changed += (sender, args) =>
{
if (args.FullPath != file.FullName)
return;
file.Refresh();
subscriber.OnNext(args.ChangeType);
};
watcher.Error += (sender, args) =>
{
subscriber.OnError(
args.GetException()
);
};
disposal.Add(
Disposable.Create(() =>
{
subscriber.OnCompleted();
})
);
watcher.EnableRaisingEvents = true;
return disposal;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment