ursus
05/02/2025, 4:09 PMappInForeground
.collectLatest { isInForeground ->
if (isInForeground) {
val webSocketSession = ktorClient.webSocketSession(..)
webSocketSession listenAndSend(webSocketSession)
}
}
is this enough? or does it need cancelling / closing explicitly? Since the WebSocketSession implements CoroutineScope im not suresimon.vergauwen
05/02/2025, 4:41 PMwebSocket
function that takes a callback, and not the one that creates a session explicitly.
https://api.ktor.io/ktor-client/ktor-client-core/io.ktor.client.plugins.websocket/[…]ck:%20suspend%20DefaultClientWebSocketSession.()%20-%3E%20Unit)
In that case it happens all for you.
appInForeground
.collectLatest { isInForeground ->
if (isInForeground) {
ktorClient.webSocket(..) {
listenAndSend(this)
}
}
}
ursus
05/02/2025, 5:00 PMsimon.vergauwen
05/02/2025, 5:13 PM(just exposing the lambda param as a return value) I thought its just for ergonomicsNo, because the library wraps your lambda in
try/finally
to close the session which it cannot do when returning the value.
Indeed please don't cross post like that. Thank you.ursus
05/02/2025, 8:52 PMconnectAndStartListening()
(via collectLatest)
private suspend fun connectAndStartListening() {
ktorClient.webSocket(urlString = wsUrl) {
listenAndSend(this)
}
}
this yields CloseReason(reason=CLOSED_ABNORMALLY, message=Connection was closed without close frame) on server
vs
private suspend fun connectAndStartListening() {
var webSocketSession: DefaultClientWebSocketSession? = null
try {
webSocketSession = ktorClient.webSocketSession(urlString = wsUrl)
listenAndSend(webSocketSession)
} finally {
webSocketSession?.close()
webSocketSession?.incoming?.cancel()
}
}
this yields CloseReason(reason=NORMAL, message=)
any idea why? or which behavior is more desirable?ursus
05/02/2025, 9:04 PMclose
is not actually called at all (when in the first variant: webSocket { }
), since the coroutine was cancelled & first suspension point (close
in finally block) should return right away and do nothing
no?
but then as im typing this, it makes no sense as the 2nd variant also calls a suspend function in finally blockursus
05/03/2025, 12:37 AMsend(close frame)
throws right aways and flush is never called, so its basically pointless imo; and the CLOSED_ABNORMALLY is called in some other finally unwinding some place elseursus
05/03/2025, 1:13 AMCloseReason(reason=INTERNAL_ERROR, message=Client failure)
on cancellationAleksei Tirman [JB]
05/05/2025, 7:48 AMursus
05/05/2025, 10:35 AM