Add support for watching watchers

This commit is contained in:
Edwin Jakobs
2020-01-10 18:45:34 +01:00
parent 49b34ed902
commit 6ea322608f

View File

@@ -19,6 +19,8 @@ class FileWatcher(private val program: Program, val file: File, private val onCh
SensitivityWatchEventModifier.HIGH SensitivityWatchEventModifier.HIGH
) )
} }
val watchers = mutableListOf<() -> Unit>()
init { init {
watchThread watchThread
watching.getOrPut(path) { watching.getOrPut(path) {
@@ -34,11 +36,12 @@ class FileWatcher(private val program: Program, val file: File, private val onCh
internal fun triggerChange() { internal fun triggerChange() {
program.launch { program.launch {
onChange(file) onChange(file)
watchers.forEach { it() }
} }
} }
} }
private val watchers = mutableMapOf< ()->Any, FileWatcher>() private val watchers = mutableMapOf<() -> Any, FileWatcher>()
fun <T> watchFile(program: Program, file: File, transducer: (File) -> T): () -> T { fun <T> watchFile(program: Program, file: File, transducer: (File) -> T): () -> T {
var result = transducer(file) var result = transducer(file)
@@ -55,25 +58,40 @@ fun <T> watchFile(program: Program, file: File, transducer: (File) -> T): () ->
} }
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
watchers[function as ()->Any] = watcher watchers[function as () -> Any] = watcher
return function return function
} }
/** /**
* Stops the watcher * Stops the watcher
*/ */
fun <T> (()->T).stop() { fun <T> (() -> T).stop() {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
watchers[this as ()->Any]?.stop() watchers[this as () -> Any]?.stop()
} }
/** /**
* Triggers reload * Triggers reload
*/ */
fun <T> (()->T).triggerChange() { fun <T> (() -> T).triggerChange() {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
watchers[this as ()->Any]?.triggerChange() watchers[this as () -> Any]?.triggerChange()
}
/**
* add watcher to file watcher
*/
fun <T, R> (() -> 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() it.readText()
} }
a.stop() a.stop()
a.triggerChange() a.triggerChange()