Correct me if I'm wrong, but there doesn't seem to...
# kotlin-native
s
Correct me if I'm wrong, but there doesn't seem to be a way to call a non-static and capturing function on program exit in kotlin/native.
o
You can read such lambda from the global, although
s
I have a class that needs to send a close notice to its websocket connection before the program exits. This is doable on JVM, as I can add a hook to the program exit and run that operation, but I can't perform the same on kotlin/native due to its non-static and capturing nature.
I can't store a collection of websocket sessions in the class's companion object due to objects being frozen by default, either. It seems like there's genuinely no way to accomplish this.
o
Is it UI program?
s
It’s a library that’s intended to be used from the command line, but a frontend for it could in theory have a UI. The entire system is non-blocking and relies heavily on structured concurrency.
o
The its likely not how it shall be done in general. If you have structural concurrency, then resource mgmt shall be structural too.
Adding state to global list (on exit handlers) is not the best idea. Why not implement smth like https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/mem-scoped.html but for websockets
s
You’ve got a point. The main issue I see is that I don’t know where I’d even begin if I wanted to implement something like that, especially in the context of multiplatform.
If you have any suggestions, I’d be happy to hear them. I’m very interested in the idea of scoping websockets in such a way.
o
It’s rather simple and generic - create resource manager class (like MemScope in above example) which returns a resource and write function taking extension lambda on that class, and freeing resource after executing it. Understand how memScoped works, then things will be pretty clear.
s
I'll see what I can do. Thank you for the suggestion, I really appreciate it!
So it looks like the resources are released in that
finally
block within the function. On JVM, the
finally
block doesn’t execute on process exit if it’s within a coroutine. Is this behavior different in kotlin/native?