Predict the output
The child that loads reviews throws. What happens to the other child and to loadPage?
suspend fun loadPage(): Page = coroutineScope {
val details = async { api.details() } // 2 s
val reviews = async { api.reviews() } // throws after 0.5 s
Page(details.await(), reviews.await())
}Hint 1 of 2
What does a failing child do to its parent?
Hint 2 of 2
What does the parent then do to its other children?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A details is cancelled and loadPage throws the reviews error
Correct. A failing child cancels its siblings, and coroutineScope rethrows the failure.
Why not the others?
- B details keeps running and loadPage returns a Page without reviews. That would need supervisorScope plus try/catch around reviews.await().
- C loadPage waits for details, then throws. The sibling is cancelled at once, not awaited to completion.
- D The error is ignored until someone calls await on reviews. In coroutineScope, the failure cancels the scope straight away.
Text version
With coroutineScope (reviews fails)
- reviews throws
- The scope is cancelled
- details is cancelled
- loadPage rethrows the error
loadPage scope: ✕ faileddetails: ⊘ cancelledreviews: ✕ failed
With supervisorScope (reviews fails)
- reviews throws
- The supervisor ignores it for the other child
- details completes
- reviews.await() throws where you call it
loadPage scope: ● activedetails: ✓ completedreviews: ✕ failed