I want to receive data sent to a given route using...
# ktor
m
I want to receive data sent to a given route using a flow,
Copy code
fun Routing.getFlow() = callbackFlow<String> {
    val route = this@getFlow
    route.get("/example") {
        try {
            send("Received GET request at /example")
        } catch (e: Exception) {
            close(e)
        }
    }
    awaitClose()
}
Is this the correct way (creating route inside a callback flow) to do it or does this have any drawbacks?
a
The routes must be created on the server startup but your code might violate this rule. Can you describe what problem are you trying to solve?
m
@Aleksei Tirman [JB] I am trying to read the data received in the route for other operations. For eg. I receive type A in my route, The route processes and responds according, besides this, I want to process the data A seperately, like say I want to convert it to type B and save it to database.
Another usage I want is that, I have a route and a websocket, so whatever data I receive in the routes, I want to send it to the clients connected to the websocket.
a
You could try using a
MutableSharedFlow
instead
Copy code
embeddedServer(Netty, port = 8080) {
        data class ReceivedRequest(
            val httpMethod: HttpMethod,
            val path: String,
        )
        val receivedRequests = MutableSharedFlow<ReceivedRequest>()
        launch {
            receivedRequests.collect { receivedRequest ->
                println("Received request: $receivedRequest")
                // save to database or whatever here
            }
        }
        install(WebSockets)
        routing {
            webSocket("/ws") {
                receivedRequests.collect { receivedRequest ->
                    send("received request $receivedRequest")
                }
            }
            get("/example") {
                receivedRequests.emit(ReceivedRequest(call.request.httpMethod, call.request.path()))
                call.respondText("Hello World!")
            }
        }
    }.start(true)
🙌 1