From c30c71ac0dc2ef4605d604f927f369463fc8a506 Mon Sep 17 00:00:00 2001 From: Edwin Jakobs Date: Sat, 8 Feb 2020 13:29:11 +0100 Subject: [PATCH] Add event debouncing for orx-file-watcher --- orx-file-watcher/src/main/kotlin/FileWatcher.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/orx-file-watcher/src/main/kotlin/FileWatcher.kt b/orx-file-watcher/src/main/kotlin/FileWatcher.kt index f09e3fda..b6f9f734 100644 --- a/orx-file-watcher/src/main/kotlin/FileWatcher.kt +++ b/orx-file-watcher/src/main/kotlin/FileWatcher.kt @@ -1,6 +1,10 @@ package org.operndr.extras.filewatcher import com.sun.nio.file.SensitivityWatchEventModifier +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import org.openrndr.Program import org.openrndr.launch import java.io.File @@ -101,6 +105,7 @@ fun Program.watchFile(file: File, transducer: (File) -> T): () -> T = watchF private val watching = mutableMapOf>() private val pathKeys = mutableMapOf() private val keyPaths = mutableMapOf() +private val waiting = mutableMapOf() private val watchService by lazy { FileSystems.getDefault().newWatchService() @@ -114,8 +119,16 @@ private val watchThread by lazy { key.pollEvents().forEach { val contextPath = it.context() as Path val fullPath = path?.resolve(contextPath) - watching[fullPath]?.forEach { w -> - w.triggerChange() + + fullPath?.let { + waiting[fullPath]?.cancel() + + waiting[fullPath] = GlobalScope.launch { + delay(100) + watching[fullPath]?.forEach { w -> + w.triggerChange() + } + } } } key.reset()