ursus
03/12/2025, 11:35 PMprivate suspend fun connectAndStartListening() = coroutineScope {
val webSocketSession = ktorClient.webSocketSession("<ws://10.0.2.2:8765>")
launch {
for (frame in webSocketSession.incoming) {
Log.d("Default", "frame=$frame")
}
}
... stuff
}
I want to add graceful closing when this coroutine gets cancelled. How do I listen for cancellation of this function?
launch {
awaitCancellation()
webSocketSession.close()
}
like this?Zach Klippenstein (he/him) [MOD]
03/12/2025, 11:55 PMprivate suspend fun connectAndStartListening() {
val webSocketSession = ktorClient.webSocketSession("<ws://10.0.2.2:8765>")
// Assuming the session implements AutoCloseable
webSocketSession.use {
coroutineScope {
launch {
for (frame in webSocketSession.incoming) {
Log.d("Default", "frame=$frame")
}
}
... stuff
}
}
}
ursus
03/12/2025, 11:58 PMpublic interface WebSocketSession : CoroutineScope
so.. I dont think so?
also now im noticing, close
is a suspend function
public suspend fun WebSocketSession.close(reason: CloseReason = CloseReason(CloseReason.Codes.NORMAL, ""))
Zach Klippenstein (he/him) [MOD]
03/12/2025, 11:59 PMuse
with try/finallyursus
03/13/2025, 12:03 AMZach Klippenstein (he/him) [MOD]
03/13/2025, 12:04 AMursus
03/13/2025, 12:05 AMZach Klippenstein (he/him) [MOD]
03/13/2025, 12:12 AMZach Klippenstein (he/him) [MOD]
03/13/2025, 12:13 AMursus
03/13/2025, 12:18 AMursus
03/13/2025, 12:24 AMprivate suspend fun listenAndSend(webSocketSession: DefaultClientWebSocketSession) = coroutineScope {
val channel = Channel<ByteArray>(capacity = Channel.BUFFERED)
launch {
while (isActive) {
val bytes = queryMicrophone()
channel.send(bytes)
}
channel.close()
}
for (bytes in channel) { <-------
webSocketSession.send(bytes)
}
}
If I may follow up
would you wrap this loop in launch or not?Zach Klippenstein (he/him) [MOD]
03/13/2025, 12:45 PMursus
05/03/2025, 12:54 AM