Created
January 19, 2018 09:03
-
-
Save tintoy/fbc565547e9a2da259cafe6ff1a96bda to your computer and use it in GitHub Desktop.
IObservable for file-change notifications
This file contains hidden or 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
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