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

asad.awadia

03/23/2019, 5:18 AM
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

octylFractal

03/23/2019, 5:49 AM
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

asad.awadia

03/23/2019, 5:54 AM
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

octylFractal

03/23/2019, 5:58 AM
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

oshai

03/23/2019, 8:15 AM
Javalin support CompletableFuture and there is a bridge between coroutines and cf
14 Views