Why is the IDE complaining of *blocking call* when...
# ktor
m
Why is the IDE complaining of blocking call when I'm not specifying the Dispatcher for
async
? (When I am already in the
context
of the IO Dispatcher)?
g
It’s not so smart to detect such case
How actual code looks like? Because this from sample doesn’t make sense itself, or you have multiple async there?
I would recommend instead of wrapping with Dispatcher.IO whole block, write an extension fucntion which does it for GeocodingApiRequest. Like:
Copy code
suspend fun <T> GeocodingApiRequest<T>.awaitAsync() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
   await()
}
It’s not so different, but instead of wrapping to IO where you use it, in final code you use already async code and don’t worry about dispatchers
m
There's no extra code. It's the same code in a suspend function.
You mean I can ignore this warning?
g
yes, you can ignore this warning, it’s just false positive
,analysis is not advanced enough to understand that this async uses the same dispatcher as parent scope\
There’s no extra code. It’s the same code in a suspend function.
But in this case you don’t need async, it does nothing, just unnecessary wrapping withContext is enough
in 99% cases async{}.await() (so await right after async creation) is unnecessary and can be replaced withContext
😍 1
d
Protip: Use
runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>)
instead of
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
when blocking.
g
it will help only if this blocking API supports thread interruption, which is not a very common case
d
True but does it hurt to do it all the time?
g
a bit less efficient, but not a big deal But may create a false sense that this operation will be interrupted
d
Alright, more stuff to keep in mind.
g
Actually, even better in case of GeocodingApiRequest, introduce proper, non-blocking api
1
because essentially this is a kind of Future, so no need to block at all and just use suspendCancellableCoroutine
d
Ah, nice. No need for wasteful blocking.
m
@gildor Thanks a ton
g
@manlan This how such adapter may look like (it will work with any Google Maps APIs which use PendingResult) https://gist.github.com/gildor/7aca7499632056235cf7c8b3b3d92e29
😍 1
🙂 1