How should I be saving a file so that it doesn't hang the main thread, but also doesn't overwrite with stale data

34 Views Asked by At

So I'm working on an app using Jetbrains Desktop Compose and I've reached a stall where I cannot figure out what method I should be using to save the information. I need it to autosave whenever a change is made. My method has been to write a save function that I can call after the submit button on the dialogs I'm using for the user to change the object. There might be a better way where I watch if the object has been changed but that's besides the point.

The issue itself is this. If I call the save function with a huge object that then has to be converted to Json and outputted to a file, the main thread may hang and cause the whole app to become unresponsive. The solution to this is to do it asynchronously but that introduces the second problem: if two save requests happen close together the first may get delayed while the second goes through at which point it will overwrite the file with its old stale data and if the user closes without saving again that data will be lost. What I want to do is set it up like a queue so that if a new save request comes in before the previous one finishes the new save request waits until the old save request is finished. I've looked through all the documentation I can find but its impossible for me to work out what features are necessary. I can't tell if I need to be using Jobs, promises, channels, or another of the various coroutine related features kotlin has.

any ideas?

1

There are 1 best solutions below

0
On

I guess the simplest solution would be to use a Mutex

val mutex = Mutex()

susped fun saveData(data: String) = mutex.withLock {
    // TODO: save data
}

An alternative solution is to use a Channel, have a coroutine that sends the data to be saved to the channel, and a different coroutine that reads from the channel and does the saving Note: the coroutine that reads should run on a single thread.