withContext
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T (source)
Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.
suspend fun <R> coroutineScope(
block: suspend CoroutineScope.() -> R
): R (source)
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.
the withContext takes CoroutineContext, and both seems to be complete
after all its children are complete.
In what case the withContext
or the coroutineScope
should be preferred than the other?
for example:
suspend fun processAllPages() = withContext(Dispatchers.IO) {
// withContext waits for all children coroutines
launch { processPages(urls, collection) }
launch { processPages(urls, collection2) }
launch { processPages(urls, collection3) }
}
could also be
suspend fun processAllPages() = coroutineScope {
// coroutineScope waits for all children coroutines
launch { processPages(urls, collection) }
launch { processPages(urls, collection2) }
launch { processPages(urls, collection3) }
}
are the both processAllPages()
doing the same?
update: see discuss at Why does withContext await for the completion of child coroutines
coroutineScope()
"It's used to decompose a task into several concurrent subtasks.", does this also apply towithContext()
? Besides thatwithContext()
can specify context they both suspend until all children coroutines complete. Seems they both could be used in the places if context does not matter, isnt it? ForwithContext()
it also mentions"This suspending function is cancellable."
, does it implies it will be cancelled if the parent/call is cancelled? I guess inwithContext()
one sub-coroutines fails would not cancel its siblings. – Burgonet