FileWatcher

class FileWatcher(file: File, debounceMs: Long = 500, onReload: () -> Unit)

Watches a single file for modifications and triggers a debounced reload callback.

Uses the Java NIO WatchService to monitor the parent directory for ENTRY_MODIFY events. Only events matching the target file name are processed; all others are ignored.

Debounce behavior: When a file modification is detected, the onReload callback is scheduled to run after debounceMs milliseconds. Rapid successive modifications within the debounce window are collapsed into a single reload, preventing redundant reloads during multi-write save operations.

Threading: The watcher runs on a single daemon thread named kconfig-watcher-<filename>. Because the thread is a daemon, it does not prevent JVM shutdown. The thread polls for events every 1 second.

Lifecycle:

  1. Create a FileWatcher instance.

  2. Call start to begin monitoring. Calling start multiple times is safe (no-op).

  3. Call stop to terminate the watcher, shut down the thread pool, and close the watch service. The watcher cannot be restarted after stopping.

Example:

val watcher = FileWatcher(File("config.yml"), debounceMs = 1000) {
println("Config file changed, reloading...")
// reload logic here
}
watcher.start()

//Later, to stop watching:
watcher.stop()

Since

1.0

Parameters

file

The file to watch for modifications.

debounceMs

The debounce delay in milliseconds. Defaults to 500.

onReload

The callback invoked when the file is modified (after debounce).

See also

Constructors

Link copied to clipboard
constructor(file: File, debounceMs: Long = 500, onReload: () -> Unit)

Functions

Link copied to clipboard
fun start()

Starts watching the file for modifications.

Link copied to clipboard
fun stop()

Stops watching the file and releases all resources.