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

walla

03/14/2019, 7:15 AM
Hi! How much does it make sense to do all the work with databases inside withContext(Dispatchers.IO) block? I mean backend application.
g

gildor

03/14/2019, 7:17 AM
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

walla

03/14/2019, 7:23 AM
Thanks
j

Jorge Bo

02/25/2022, 1:09 PM
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

gildor

02/25/2022, 2:37 PM
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

Jorge Bo

02/25/2022, 2:38 PM
cool
g

gildor

02/25/2022, 2:40 PM
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

Jorge Bo

02/25/2022, 2:42 PM
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

gildor

02/25/2022, 2:45 PM
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

Jorge Bo

02/25/2022, 2:48 PM
thanks, for the info it was very helpful
g

gildor

02/25/2022, 2:48 PM
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

Jorge Bo

02/25/2022, 3:07 PM
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

gildor

02/25/2022, 3:29 PM
Yep, it's completely fine
🙌 1
2 Views