https://kotlinlang.org logo
#ktor
Title
# ktor
o

obobo

02/25/2019, 9:48 PM
Hi, I have a question on how and why to use dispatchers. I have a ktor project in which I fetch a number of results from the database, then I need to split these results and send them to a separate service, waiting for the response. I've implemented this using Deferreds, and using awaitall() on them. My current implementation creates a
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
and then uses
async
on it to create the Deferreds. My question is whether this is the correct way to do this, or if I should use the
coroutineScope
function to create the scope and call
async
from within. Unsure if this is a #ktor or #coroutines question, seems more like the former.
b

bdawg.io

02/25/2019, 10:56 PM
This is a #coroutines question, but I would recommend doing
Copy code
routing {
    get { // `this` is a CoroutineScope already
        // inside of your handler
        val one = async(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
        val two = async(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
        val three = async(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
    }
}
this attaches your
async
coroutines to be part of your route’s lifecycle
alternatively you could wrap your
async
builders using
with
to reduce duplication of which dispatcher to use
Copy code
routing {
    get {
        val results = with(CoroutineScope(coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>)) {
            val one = async { ... }
            val two = async { ... }
            val three = async { ... }
            listOf(one, two, three)
        }.awaitAll()
    }
}
👍 1
2 Views