https://kotlinlang.org logo
Title
m

mingkangpan

12/04/2018, 12:10 PM
fun main() {
    runBlocking {
       val foo1 = withContext(IO) {
           delay(100)
           "foo1"
       }

       val fooDeferred = async(IO) {
            delay(100)
            "foo2"
       }

       val foo2 = fooDeferred.await()
       print("$foo1 and $foo2")
    }
}
^ can someone tell me, what the different here between
async(IO)
and
withContext(IO)
? only that async is deferred?
d

Dominaezzz

12/04/2018, 12:14 PM
Pretty much. You can think of
withContext
as an optimization, for when you immediately await an async.
Or better put.
withContext
is used when you want to switch contexts but not create a new coroutine.
z

zokipirlo

12/04/2018, 12:51 PM
withContext is running blocking... look at example https://goo.gl/R8E1Dq
g

gildor

12/04/2018, 1:53 PM
No I would say that analogy withContext as optimization for await/async is wrong way to think about this, because with context not create any coroutines, it's just a way to update context
d

Dominaezzz

12/04/2018, 1:55 PM
I agree. That's why I clarified.