https://kotlinlang.org logo
Title
n

Nikolay Lebedev

10/27/2021, 9:37 PM
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

Andreas Scheja

10/27/2021, 10:22 PM
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

Nikolay Lebedev

10/27/2021, 11:19 PM
@Andreas Scheja Can you please give an example of how this handler should look like?
a

Andreas Scheja

10/28/2021, 12:04 AM
something like this should work I think
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