Hii! When using Ktor Server, what is the best way ...
# ktor
j
Hii! When using Ktor Server, what is the best way to run two tasks in parallel and wait for the result, inside an endpoint? I have tried multiple variations of this:
Copy code
val result = runBlocking(this.coroutineContext.newCoroutineContext(<http://Dispatchers.IO|Dispatchers.IO>)) {
    val resultOne = async { 
        ...
    }
    val resultTwo = async { 
        ...
    }
    return@runBlocking Pair(resultOne.await(), resultTwo.await())
}
But it seems it always blocks other requests and the server stops responding when handling lots of parallel requests. Any help is appreciated, thanks!!
c
You should run it in the requests context and not run it blocking.
j
Ahh I think I figured it out:
Copy code
val result = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val resultOne = async { 
        ...
    }
    val resultTwo = async { 
        ...
    }
    return@withContext Pair(resultOne.await(), resultTwo.await())
}
runBlocking
is not needed since it's already in Ktor's coroutine (I think)
p
Never used Ktor but the standard way for parallel decomposition of work is
coroutineScope {}
or
supervisorScope {}
.
withContext
is to be used when you want to change context
a
Copy code
embeddedServer(Netty, host = "localhost", port = 9090) {
    routing {
        get {
            val tasks = mutableListOf<Deferred<*>>()
            tasks.add(async {
                delay(500)
                println("task1")
            })
            tasks.add(async {
                delay(1000)
                println("task2")
            })

            tasks.awaitAll()
            call.respondText { "OK" }
        }
    }
}.start(wait = true)