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
Chrimaeon
08/13/2023, 11:21 AM
You should run it in the requests context and not run it blocking.
j
Josep Rovira
08/13/2023, 2:51 PM
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
Patrick Steiger
08/13/2023, 3:16 PM
Never used Ktor but the standard way for parallel decomposition of work is