Skip to content

Commit

Permalink
Fix error in FileChangeDetection
Browse files Browse the repository at this point in the history
  • Loading branch information
sdercolin committed Jul 22, 2024
1 parent 858cf0f commit 46844f1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 30 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ kotlin.code.style=official
kotlin.version=1.9.23
agp.version=7.1.3
compose.version=1.6.2
app.version=1.4.0-beta1
app.version=1.4.0-beta2
Original file line number Diff line number Diff line change
Expand Up @@ -28,38 +28,46 @@ class FileChangeDetection(
return
}
job = coroutineScope.launch(Dispatchers.IO) {
val watchService = FileSystems.getDefault().newWatchService()
val directoryPath = Paths.get(directory.absolutePath)
directoryPath.register(watchService, ENTRY_CREATE, ENTRY_MODIFY)
while (isActive) {
val key = watchService.take()
yield()
val new = mutableListOf<File>()
val changed = mutableListOf<File>()
key.pollEvents().forEach { event ->
val kind = event.kind()
val path = event.context() as Path
val file = directory.resolve(path.toString())
if (filter(file).not()) {
return@forEach
}
when (kind) {
ENTRY_CREATE -> new.add(file)
ENTRY_MODIFY -> changed.add(file)
}
Log.debug("File change detected: new=$new, changed=$changed")
if (callbackJob?.isActive == true) {
Log.debug("File change detection callback is already running, skipping")
} else {
callbackJob = coroutineScope.launch {
callback.onFileChanged(changed, new)
runCatching {
if (directory.isDirectory.not()) {
Log.info("Creating directory $directory during file change detection")
directory.mkdirs()
}
val watchService = FileSystems.getDefault().newWatchService()
val directoryPath = Paths.get(directory.absolutePath)
directoryPath.register(watchService, ENTRY_CREATE, ENTRY_MODIFY)
while (isActive) {
val key = watchService.take()
yield()
val new = mutableListOf<File>()
val changed = mutableListOf<File>()
key.pollEvents().forEach { event ->
val kind = event.kind()
val path = event.context() as Path
val file = directory.resolve(path.toString())
if (filter(file).not()) {
return@forEach
}
when (kind) {
ENTRY_CREATE -> new.add(file)
ENTRY_MODIFY -> changed.add(file)
}
Log.debug("File change detected: new=$new, changed=$changed")
if (callbackJob?.isActive == true) {
Log.debug("File change detection callback is already running, skipping")
} else {
callbackJob = coroutineScope.launch {
callback.onFileChanged(changed, new)
}
}
}
val valid = key.reset()
if (!valid) {
break
}
}
val valid = key.reset()
if (!valid) {
break
}
}.onFailure {
Log.error(it)
}
}
}
Expand Down

0 comments on commit 46844f1

Please sign in to comment.