Hi I'm beginner in kotlin i use ktor client how to...
# ktor
u
Hi I'm beginner in kotlin i use ktor client how to detect connection close if on js we can do socket.onclose
Copy code
fun listenWebsocketEvents(): Flow<String> = flow {
    _client.webSocket(
        method = HttpMethod.Get,
        host = _host,
        port = _port,
        path = "/api/ws?token=xyz"
    ) {
        try {
            val sendJob = launch {
                _messageFlow.collect { message ->
                    send(Frame.Text(message))
                }
            }

            for (frame in incoming) {
                Log.d("ChatScreen", "Received frame: $frame")
                when (frame) {
                    is Frame.Text -> {
                        Log.d("ChatScreen", "Received message: ${frame.readText()}")
                    }

                    is Frame.Close -> {
                        Log.d("ChatScreen", "WebSocket closed")
                        break
                    }

                    else -> Unit
                }
            }

            sendJob.cancel()
        } catch (e: ClosedReceiveChannelException) {
            Log.d("ChatScreen", "WebSocket closed")
        }
    }
}
a
You can add code within the
finally
clause of the
try/catch
block, which will be executed when the connection is closed.