coroutineScope (Function)
See Coroutine scope function and Error Boundary for detailed info on scope functions.
- Inherits a context from its parent, while creating a new Regular Job that inherits from parent Job.
- Uncaught Exception from one child:
- Waits for all its children before it can finish itself (when children do not throw)
- Cancels all its children when the parent is cancelled
From pseudo-code to illustrate what coroutineScope
Go to text ā
// This is pseudo-code for purposes of understanding !!NOT TO BE USED AS IS!!
suspend fun <T> coroutineScope(block: suspend CoroutineScope.() -> T): T {
// Get the current coroutine context
val currentContext = coroutineContext
// Create a new Job that's a child of the current job
val scopeJob = Job(parent = currentContext[Job])
// Create a new scope with the new job
val scope = CoroutineScope(currentContext + scopeJob)
try {
// Execute the block and get result
val result = block(scope)
// This conceptually "waits" for all children to complete
// (In reality this would need to be done differently)
scopeJob.complete() // Signal no more children will be added
scopeJob.join() // Wait for existing children
return result
} catch (e: Exception) {
// Cancel all children on any exception
scopeJob.cancelChildren()
throw e
}
}
Children
- coroutineScope: cancellation-exception-only-stops-the-throwing-child
- coroutineScope: cancels all its children when the parent is cancelled
- coroutineScope: cancels other children when one throws Uncaught Exception (non cancellation exception)
- coroutineScope: waits for all its children before it can finish itself (when children do not throw)
- pseudo-code to illustrate what coroutineScope
Backlinks