Why can't we call `launch` or `async` from `suspen...
# coroutines
n
Why can't we call
launch
or
async
from
suspend
function directly.
suspend
functions get called from a
coroutine
. Why can't it use that context. If we create a new
coroutineScope
inside a
suspend
function then would the new
coroutines
be attached to the parent that called the
suspend
function? So that these get cancelled when the parent get cancelled.
j
The coroutine context is different from the coroutine's scope. The scope is rather about the lifetime of the coroutine (when it terminates). Using
coroutineScope
, nested coroutines do inherit the current coroutine's context, but you're also limiting these nested coroutines' scope to the
coroutineScope
block (all child coroutines have to end before coroutineScope can resume). That scope is indeed a child of the current coroutine's scope, so if the parent is cancelled, the children will be cancelled too. If child coroutines could be launched without a scope by reusing the parent scope directly, it would be hard to tell when they end. Suspend functions, by convention, need to finish their work before returning
👍 2
j
That and compile time safety. Launch and async aren't keywords but functions that are part of CoroutineScope. You can only call those on a co-routine scope. The coroutineScope { ... } function gets you the current scope and passes it as
this
into the block. This is a key concept with the co-routine library and structured concurrency: you can't call these functions in the wrong place (outside a co-routine scope) without introducing compile errors.
3
☝️ 1
👍 1
j
+1 to that, although the question seems to be about the reason why it is designed like this. The compiler already provides
coroutineContext
inside suspend functions only. So if it were about context, it could have been designed so that coroutine builders work on coroutine contexts and there would be just as much compile time safety as the current state.
o