I ported the JS code logic to kotlin, but the underlying websocket implementation has a bit different behavior compared to the browser web socket (in how lifecycle events are emited).
What I ended doing is when there is an error (not a regular error response from the server), I throw away both the channel and the socket (I call leave on channel and disconnect on socket and create new ones).
I didn’t have time to pinpoint the issue and patch my library.
As for your code, I see nothing wrong with it.