From 6ea322608fb3c8450d1001281edcca52dcefcded Mon Sep 17 00:00:00 2001 From: Edwin Jakobs Date: Fri, 10 Jan 2020 18:45:34 +0100 Subject: [PATCH] Add support for watching watchers --- .../src/main/kotlin/FileWatcher.kt | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/orx-file-watcher/src/main/kotlin/FileWatcher.kt b/orx-file-watcher/src/main/kotlin/FileWatcher.kt index c2d148a4..f09e3fda 100644 --- a/orx-file-watcher/src/main/kotlin/FileWatcher.kt +++ b/orx-file-watcher/src/main/kotlin/FileWatcher.kt @@ -19,6 +19,8 @@ class FileWatcher(private val program: Program, val file: File, private val onCh SensitivityWatchEventModifier.HIGH ) } + val watchers = mutableListOf<() -> Unit>() + init { watchThread watching.getOrPut(path) { @@ -34,11 +36,12 @@ class FileWatcher(private val program: Program, val file: File, private val onCh internal fun triggerChange() { program.launch { onChange(file) + watchers.forEach { it() } } } } -private val watchers = mutableMapOf< ()->Any, FileWatcher>() +private val watchers = mutableMapOf<() -> Any, FileWatcher>() fun watchFile(program: Program, file: File, transducer: (File) -> T): () -> T { var result = transducer(file) @@ -55,25 +58,40 @@ fun watchFile(program: Program, file: File, transducer: (File) -> T): () -> } @Suppress("UNCHECKED_CAST") - watchers[function as ()->Any] = watcher + watchers[function as () -> Any] = watcher return function } /** * Stops the watcher */ -fun (()->T).stop() { +fun (() -> T).stop() { @Suppress("UNCHECKED_CAST") - watchers[this as ()->Any]?.stop() + watchers[this as () -> Any]?.stop() } /** * Triggers reload */ -fun (()->T).triggerChange() { +fun (() -> T).triggerChange() { @Suppress("UNCHECKED_CAST") - watchers[this as ()->Any]?.triggerChange() + watchers[this as () -> Any]?.triggerChange() +} + + +/** + * add watcher to file watcher + */ +fun (() -> T).watch(transducer: (T) -> R):()->R { + + var result = transducer(this()) + + watchers[this as () -> Any?]!!.watchers.add { + result = transducer(this()) + } + + return { result } } @@ -110,6 +128,7 @@ fun main() { it.readText() } + a.stop() a.triggerChange()