Created
November 15, 2015 12:33
-
-
Save disc99/f36db7dd6116ad4a69da to your computer and use it in GitHub Desktop.
This file contains 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
import java.nio.file.WatchEvent; | |
public class FileSystemEvent { | |
WatchEvent<?> watchEvent; | |
FileSystemEvent(WatchEvent<?> watchEvent) { | |
this.watchEvent = watchEvent; | |
} | |
} |
This file contains 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
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