What are differences of use between down below cod...
# coroutines
u
What are differences of use between down below code? and What case should i use withContext not coroutine builder like async?
Copy code
/-- no1
val job = async(dispatcher) { /**  do something */ }
/** do other processes */
val result = job.await()

/-- no2
val result = withContext(dispatcher) { /**  do something */ }
j
They don't do the same thing at all, so it's hard to answer the question. The first one is a way to run 2 pieces of code concurrently (the code inside async runs concurrently with the code between the end of the async block and the await). The second one runs a single piece of code in a different context, and what comes after runs again in the old context. There is no concurrency involved in this construct.
So about choosing the correct one, just use the one that does what you need. Sometimes you need to start a new coroutine to run things concurrently, in which case you should use a coroutine builder. Sometimes you just want to switch to another context (e.g. another dispatcher) temporarily, in this case use
withContext
👆🏻 1
💯 1
👀 1
c
Another way to explain the same thing:
Copy code
val job = async(dispatcher) { … }
val result = job.await()
is the same thing (but very slightly faster) than:
Copy code
val job = async {
    withContext(dispatcher) { … }
}
val result = job.await()
Therefore, your question is "what is the difference between
async { withContext(…) {…} }
and just
withContext(…) {…}
"; and the answer is "`async` creates another coroutine that runs concurrently".
👀 1
m
the difference is that async only suspends when you call await. So you can start something async, and the code immediately after will also run. When you use withContext, it will suspend, so the code after must wait its termination
👀 1
u
@CLOVIS You means, that when i don’t need run concurrently and just not blocking but suspend, i can choose just
withContext()
@Joffrey What are some examples where need to switch to a different context? Like Repository’s crud suspend functions that only run in IO Context?
j
Yes that's one example. Switching dispatchers for a given piece of code is the most common use case. But you can switch contexts for other reasons, for instance you can use
withContext(NonCancellable) { ... }
if you want to run some cleanup (suspending) code that cannot be cancelled.