https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zt

08/24/2022, 3:57 AM
I'm trying to use a websocket with ktor and I need to set up two while true loops. I've wrote this code which I thought would work but it only completes one iteration and then exits
Copy code
val eventJob = launch {
    while (true) {
        val event = try {
            when (val frame = incoming.receive()) {
                is Frame.Text -> json.decodeFromString<Message.Event>(frame.readText())
                is Frame.Close -> {
                    println("Received close frame: ${frame.readReason()}")
                    continue
                }
                else -> continue
            }
        } catch (e: Exception) {
            println("Error while receiving: ${e.message}")
            break
        }
        println("Received event: $event")
    }
}

val heartbeatJob = launch {
    while (true) {
        delay(helloMessage.data.heartbeatInterval.milliseconds)
        println("Sending heartbeat")
        sendSerialized(Message.Heartbeat)
    }
}

joinAll(eventJob, heartbeatJob)
17 Views