Hi! How much does it make sense to do all the work...
# ktor
w
Hi! How much does it make sense to do all the work with databases inside withContext(Dispatchers.IO) block? I mean backend application.
g
It makes sense to avoid blocking of Main or other threads that shouldn’t be blocked
I usually write suspend wrapper for DB or similar IO use cases to avoid potentially error-prone wrapping on call site (where you easily may forget to wrap to IO)
w
Thanks
j
Hi! Regarding this topic. Is it ok to write the following kind of code in Ktor? Or Does Ktor webclient takes care of not blocking main thread?
Copy code
override suspend fun find(searchAttributes: ProviderApi.SearchAttributes): List<ProviderApi.ItineraryDTO> =
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        <http://httpClient.post|httpClient.post>("$serverRootUri$RESOURCE_URI") {
            contentType(ContentType.parse("application/json"))
            body = searchAttributes
        }
    }
g
You don't need Dispatcher.IO for suspend functions, in this case it does nothing, Ktor has own dispatcher for all requests and it already non blocking
j
cool
g
More general rule that there is no reason to wrap suspend calls to dispatchers, suspend functions shouldn't block threads, and if some suspend function does block it's a bug of this function
j
yep, i have read about that, but wasn’t sure as i’m new to Ktor. And the only thread that i saw in logs was eventLoopGroupProxy-4-1. 👍
g
Ktor has own dispatcher + it utilizes dispatcher of HTTP client which used by different Ktor engines Some http clients are non blocking such as Netty, so they do not block threads anyway
Thread which you see is probably built in dispatcher used to dispatch client code coroutines, but under the hood uses the engine to execute actual http request
j
thanks, for the info it was very helpful
g
As I see it's actually Netty thread
So this is why you see only one, because it's non-blocking http server
🙌 1
j
just one more questions, perhaps you could give me an advice. Is it ok to write this kind of code in Ktor to execute parallel requests?
Copy code
override suspend fun find(searchAttributes: ProviderApi.SearchAttributes): List<ProviderApi.ItineraryDTO> {
    return coroutineScope {
        providers.map {
            async {
                it.find(searchAttributes)
            }
        }.awaitAll()
            .flatten()
    }
}
it.find(searchAttributes) => use Ktor webclient(netty)
g
Yep, it's completely fine
🙌 1