Umar Alfaruq
02/09/2025, 10:41 AMfun 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")
}
}
}
Aleksei Tirman [JB]
02/10/2025, 8:46 AMfinally
clause of the try/catch
block, which will be executed when the connection is closed.