I've got a bizarre file that is always the same size, with the same modified date. (some driver showing its state as a file's contents through a fake filesystem). It contains a short string that changes when the device's state changes. I don't think I can Watch the file because it is a fake filesystem. Cool so far!
I was hoping to modernize it! A changing file that may or may not have anyone listening feels like a flow.
I'm not entirely sure about distinctUntilChanged and conflate (do they play nice together?) and if I'm just reinventing a StateFlow?
fun fileChanges(file: File): Flow<String> = flow {
while (true) {
emit(file.readText(charset))
delay(1)
}
}
.flowOn(Dispatchers.IO) // Run in background
.distinctUntilChanged() // no duplicate status
.conflate() // only most recent
.map { it.trim() } // just the one line without newlines
This seems to work (with the expected system overhead) and I'm only trimming the deduped values, but... it smells funny. Like I should be able to reuse file handles, or memory mapped stuff, or a mark()/reset(), or better still, wrap it all up in a StateFlow object.