When using withContext, as I understand it, it doe...
# coroutines
m
When using withContext, as I understand it, it does not create a new coroutine. Does that mean that I need to launch a coroutine myself within it like so?
Copy code
suspend fun getData(): Data = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    val a = async(<http://Dispatchers.IO|Dispatchers.IO>) {
        delay(1000)
        Data("some data...")
    }
    a.await()
}
s
Instead of
withContext(...) {
, write
coroutineScope {
.
Although, your example doesn't need all this, since you only launch one async and await it at the end. But I assume your example is not the complete picture 😀
a
Unless I'm wrong,
withContext(myDispatcher){ }
will ensure that your coroutines inside the
{ }
are in the
myDispatcher
whereas
coroutineScope
will use whatever the parent context is (eg: context defined by caller perhaps). This could result in unwanted behaviours if that's not what you want. For instance, if caller used Dispatchers.Main or Dispatchers.Default but you are doing IO then it'd be better to explicitly state that your code block should run in Dispatchers.IO using withContext
m
I see, that makes sense. Would I still need
async
in either case to make sure it's a new coroutine?
s
You are already switching to the Dispatchers.IO by providing it to the async(Dispatchers.IO) call. No need to switch to it earlier. Assuming your example is not your complete code, yes, you'll need the call to async (or launch) to create a new (child) coroutine. Note that all such child coroutines must end/complete before the coroutineScope (on which the async/launch is called) can end/complete.
a
Yes well this might be a preference but I prefer
withContext
instead of specifying
<http://Dispatchers.IO|Dispatchers.IO>
in all the
lauch
and
async
within a same block of code that I know will run on the same dispatcher. Usually I will pass the coroutine scope as constructor parameter to allow dependency injection to provide it and then during test I can also use a
TestScope
from
runTest
.
Copy code
class MyImplementation(
	private val coroutineScope: CoroutineScope
) : MyInterface, CoroutineScope by coroutineScope {

	suspend fun myFun() =
		withContext(coroutineContext) {
Note that doing
async + await
is equivalent to doing
withContext
since
withContext
will start your block of code in a new coroutine and suspend until it completes. The IDE will even suggest you to use
withContext
instead if you have
async + await
right away. One last thing,
coroutineScope
has a different behaviour where if a child coroutine fails, all will be cancelled. This might or might not be what you want. From the doc : coroutineScope
Copy code
Creates a CoroutineScope and calls the specified suspend block with this scope. 
The provided scope inherits its coroutineContext from the outer scope, but overrides the context's Job.
This function is designed for parallel decomposition of work. When any child coroutine in this scope fails, this scope fails and all the rest of the children are cancelled (for a different behavior see supervisorScope).
👍 1
s
You're correct, the async+await is not needed. A plain withContext will do. I assumed that the example was not complete and the original poster was planning on launching more concurrent coroutines, not just one (the o.p. mentioned 'create and launch a new coroutine'). And you need a call to
coroutineScope
since the call to
async
requires a CoroutineScope instance as its receiver.
a
You can still launch multipe `async`/`launch` inside your
withContext
to get concurrent executions.
s
And you're correct.... 😁 My brain fart. The lambda provided to the withContext has a CoroutineScope as a receiver.
😄 1
m
Thanks a lot, all! I should've been clearer, in my example I didn't want to start a new coroutine if one was already started, which from reading the threa seems like it already does with withContext. Also coroutineScope is something I haven't learned/used yet so I'll definitely look into that. Thanks for bearing with a beginner!
a
@Muhammad Talha A coroutine is started with both
withContext
and
coroutineScope
both have this in their impl:
Copy code
val coroutine = ScopeCoroutine(uCont.context, uCont)
coroutine.startUndispatchedOrReturn(coroutine, block)
But that's just normal and if the dispatcher is the same then there wont be any new thread created and no context switching. So the main differences is the coroutine context inheritance (coroutineScope inherits the parent while withContext specifies it explicitly) and child cancellation behaviour as mentionned.
m
I see, so if say the parent scope is different from the withContext, only then it will start a new coroutine, otherwise it's pointless to call it with the same parent dispatcher (if you're only doing 1 thing inside it).
a
In all cases a coroutine is created, this is not what is expensive. What is more expensive is context switching. Here is the impl of
withContext
Copy code
public suspend fun <T> withContext(
    context: CoroutineContext,
    block: suspend CoroutineScope.() -> T
): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return suspendCoroutineUninterceptedOrReturn sc@ { uCont ->
        // compute new context
        val oldContext = uCont.context
        val newContext = oldContext + context
        // always check for cancellation of new context
        newContext.ensureActive()
        // FAST PATH #1 -- new context is the same as the old one
        if (newContext === oldContext) {
            val coroutine = ScopeCoroutine(newContext, uCont)
            return@sc coroutine.startUndispatchedOrReturn(coroutine, block)
        }
        // FAST PATH #2 -- the new dispatcher is the same as the old one (something else changed)
        // `equals` is used by design (see equals implementation is wrapper context like ExecutorCoroutineDispatcher)
        if (newContext[ContinuationInterceptor] == oldContext[ContinuationInterceptor]) {
            val coroutine = UndispatchedCoroutine(newContext, uCont)
            // There are changes in the context, so this thread needs to be updated
            withCoroutineContext(newContext, null) {
                return@sc coroutine.startUndispatchedOrReturn(coroutine, block)
            }
        }
        // SLOW PATH -- use new dispatcher
        val coroutine = DispatchedCoroutine(newContext, uCont)
        block.startCoroutineCancellable(coroutine, coroutine)
        coroutine.getResult()
    }
}
Here is the implementation of
coroutineScope
Copy code
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return suspendCoroutineUninterceptedOrReturn { uCont ->
        val coroutine = ScopeCoroutine(uCont.context, uCont)
        coroutine.startUndispatchedOrReturn(coroutine, block)
    }
}
You can see that if new context == old context, then
withContext
is pretty much like
coroutineScope
Btw there are shared threads between
<http://Dispatchers.IO|Dispatchers.IO>
and
Dispatchers.Default
to avoid context switching when possible even when context are different
🙏 1