if you have something like javalin a simple http s...
# coroutines
a
if you have something like javalin a simple http server
Copy code
import io.javalin.Javalin

fun main(args: Array<String>) {
    val app = Javalin.create().start(7000)
    app.get("/") { ctx -> ctx.result("Hello World") }
}
is it possible somehow to add coroutine support to this i.e. each request gets launched in its own coroutine and allows me to have controllers which are composed of suspending functions - maybe allow me to return a response on the context object from a launched coroutine?
o
if Javalin supports a delayed/async response, you could just call
launch
on your app scope, but if not you'll have to use
runBlocking
a
Copy code
fun main(args: Array<String>) = runBlocking {
    val app = Javalin.create().start(8080)
    val channel = Channel<Context>()
    repeat(5) { launch(<http://Dispatchers.IO|Dispatchers.IO>) {  workers(channel) } }
    app.get("/") {
        launch {
            channel.send(it)
        }
    }

    return@runBlocking
}

suspend fun workers(receiveChannel: ReceiveChannel<Context>) {
    for (c in receiveChannel) {
        c.result("foobar")
    }
}
I have this -- but it doesn't send foobar as the response
o
as I said, that only works if Javalin supports async calls to
c.result
-- it probably doesn't
https://javalin.io/documentation#asynchronous-requests you'll have to convert to a future, I think there are conversions for that built-in but I don't recall
o
Javalin support CompletableFuture and there is a bridge between coroutines and cf