Hi All! I’m very new to Kotlin and I’m trying to ...
# ktor
n
Hi All! I’m very new to Kotlin and I’m trying to write a server, which retrieves some data from database every 15 seconds and sends it to connected clients via websockets. Websocket server is running as
embeddedServer
in my main function. I guess I have to use a coroutine for regular database queries, but how do I then pass results to websocket connections?
a
I'd suggest you publish an update every 15 seconds to a
StateFlow
and then just subscribe to that flow in your websocket handler?
n
@Andreas Scheja Can you please give an example of how this handler should look like?
a
something like this should work I think
Copy code
embeddedServer(Netty, port = 8080) {
        val stateFlow = MutableStateFlow(0)
        launch {
            var i = 0
            while (isActive) {
                delay(Duration.ofSeconds(15))
                stateFlow.update { ++i }
            }
        }
        install(WebSockets)
        routing {
            webSocket("/some-route") {
                stateFlow.collect { data ->
                    println("data was updated to $data")
                    send(Frame.Text(data.toString()))
                }
            }
        }
    }.start(wait = true)
right now its only an integer that keeps increasing every 15 seconds, but you should be able to get started from there
mind blown 1