Skip to content

Instantly share code, notes, and snippets.

@disc99
Created November 15, 2015 12:33
Show Gist options
  • Save disc99/f36db7dd6116ad4a69da to your computer and use it in GitHub Desktop.
Save disc99/f36db7dd6116ad4a69da to your computer and use it in GitHub Desktop.
import java.nio.file.WatchEvent;
public class FileSystemEvent {
WatchEvent<?> watchEvent;
FileSystemEvent(WatchEvent<?> watchEvent) {
this.watchEvent = watchEvent;
}
}
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import java.io.IOException;
import java.nio.file.*;
public class FileSystemWatcher {
public static Observable<FileSystemEvent> watch(String dir, WatchEvent.Kind<?>[] events) {
return Observable.<FileSystemEvent>create(subscriber -> {
FileSystem fileSystem = FileSystems.getDefault();
try (WatchService watcher = fileSystem.newWatchService()) {
Path path = fileSystem.getPath(dir);
path.register(watcher, events);
while (true) {
WatchKey key = watcher.take();
Observable.from(key.pollEvents()).forEach(event -> subscriber.onNext(new FileSystemEvent(event)));
key.reset();
}
} catch (Throwable e) {
subscriber.onError(e);
} finally {
subscriber.onCompleted();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment