The documentation of withContext
states
Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.
However, the actual behavior is that it awaits on all the child coroutines as well, and doesn't necessarily return the result of the block but instead propagates any exception in the child coroutine.
suspend fun main() {
try {
val result = withContext(coroutineContext) {
launch {
delay(1000L)
throw Exception("launched coroutine broke")
}
println("done launching")
42
}
println ("result: $result")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
I would expect the above to print result: 42
and then, possibly, print the uncaught exception from the child coroutine. Instead it waits for one second and then prints Error: launched coroutine broke
.
The actual behavior, therefore, matches that of the coroutineScope
builder. While it may be a useful behavior, I think it contradicts the documentation. Should the documentation be updated to something similar to coroutineScope
?
This function returns as soon as the given block and all its children coroutines are completed.
Furthermore, does that mean that we can use coroutineScope
and withContext(coroutineContext)
interchangeably, the only difference being a bit less boilerplate?