https://kotlinlang.org logo
Title
m

manlan

08/14/2020, 5:26 AM
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

gildor

08/14/2020, 5:40 AM
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:
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

manlan

08/14/2020, 6:20 AM
There's no extra code. It's the same code in a suspend function.
You mean I can ignore this warning?
g

gildor

08/14/2020, 6:21 AM
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

Dominaezzz

08/14/2020, 11:57 AM
Protip: Use
runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>)
instead of
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
when blocking.
g

gildor

08/14/2020, 12:01 PM
it will help only if this blocking API supports thread interruption, which is not a very common case
d

Dominaezzz

08/14/2020, 12:02 PM
True but does it hurt to do it all the time?
g

gildor

08/14/2020, 12:06 PM
a bit less efficient, but not a big deal But may create a false sense that this operation will be interrupted
d

Dominaezzz

08/14/2020, 12:11 PM
Alright, more stuff to keep in mind.
g

gildor

08/14/2020, 12:12 PM
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

Dominaezzz

08/14/2020, 12:18 PM
Ah, nice. No need for wasteful blocking.
m

manlan

08/14/2020, 5:08 PM
@gildor Thanks a ton
g

gildor

08/15/2020, 3:38 AM
@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