Created
March 31, 2022 16:29
-
-
Save trito-dev/31c45b50b4aa7488962b717252a42cbb 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
/** | |
* Creates a flow WatchEvent from a watchService | |
*/ | |
fun WatchService.eventFlow() : Flow<List<WatchEvent<out Any>>> = flow { | |
while (currentCoroutineContext().isActive) { | |
coroutineScope { | |
var key: WatchKey? = null | |
val job = launch { | |
runInterruptible(Dispatchers.IO) { | |
key = take() | |
} | |
} | |
job.join() | |
val currentKey = key | |
if (currentKey != null) { | |
emit(currentKey.pollEvents()) | |
currentKey.reset() | |
} | |
} | |
} | |
} | |
/** | |
* Returns a flow with the files inside a folder (with a given glob) | |
*/ | |
fun Path.listDirectoryEntriesFlow(glob: String): Flow<List<Path>> { | |
val watchService = watch() | |
return watchService.eventFlow() | |
.map { listDirectoryEntries(glob) } | |
.onStart { emit(listDirectoryEntries(glob)) } | |
.onCompletion { watchService.close() } | |
.flowOn(Dispatchers.IO) | |
} | |
/** | |
* Creates a new WatchService for any Event | |
*/ | |
fun Path.watch() : WatchService { | |
return watch(StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, | |
StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_DELETE) | |
} | |
/** | |
* Creates a new watch service | |
*/ | |
fun Path.watch(vararg events: WatchEvent.Kind<out Any>) = fileSystem.newWatchService()!!.apply { register(this, events) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment