bk9735732777
01/09/2025, 2:19 AMfun test() {
coroutineScope.launch {
launch {
makeApiCall()
throwException()
}
launch {
makeApiCall2()
}
}
}
fun throwException() {
throw CancellationException("Error")
}
suspend fun makeApiCall() {
delay(2.seconds)
Log.d(TAG, "Successful Api Call")
}
suspend fun makeApiCall2() {
delay(5.seconds)
Log.d(TAG, "Successful Api Call 2")
}
What will be the output the shouldn't the second api call fail cos it is with 5 sec delay but till that time the coroutine should cancel as the exception is uncaught and it should propagate to parent right?streetsofboston
01/09/2025, 2:25 AMcoroutineScope
. If its job is a SupervisorJob, the other children won't be cancelled.bk9735732777
01/09/2025, 2:30 AMval coroutineScope = CoroutineScope(Dispatchers.Main)
bk9735732777
01/09/2025, 2:30 AMbk9735732777
01/09/2025, 2:31 AMstreetsofboston
01/09/2025, 2:34 AMbk9735732777
01/09/2025, 2:35 AMbk9735732777
01/09/2025, 2:35 AMval TAG = "CoroutinesTest"
val coroutineScope = CoroutineScope(Dispatchers.Main)
val supervisorScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
Log.d(TAG, "Caught Exception: $throwable")
}
class CoroutinesActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Box(Modifier.fillMaxSize())
}
test()
}
}
fun test() {
supervisorScope.launch(exceptionHandler) {
launch {
makeApiCall()
throwException()
}
launch {
makeApiCall2()
}
}
}
fun throwException() {
throw Exception("Error")
}
suspend fun makeApiCall() {
delay(2.seconds)
Log.d(TAG, "Successful Api Call")
}
suspend fun makeApiCall2() {
delay(5.seconds)
Log.d(TAG, "Successful Api Call 2")
}
Now this is the code snippetbk9735732777
01/09/2025, 2:36 AMbk9735732777
01/09/2025, 2:42 AMmuliyul
01/09/2025, 10:48 AMsupervisorScope { ... }
rather than what you have.bk9735732777
01/09/2025, 11:33 AMJP Sugarbroad
01/09/2025, 6:20 PMJP Sugarbroad
01/09/2025, 6:20 PMJP Sugarbroad
01/09/2025, 6:21 PMJP Sugarbroad
01/09/2025, 6:21 PMsupervisorScope.launch(exceptionHandler) {
makeApiCall()
throwException()
}
supervisorScope.launch(exceptionHandler) {
makeApiCall2()
}
muliyul
01/09/2025, 6:26 PMbk9735732777
01/10/2025, 5:12 AMJP Sugarbroad
01/10/2025, 6:41 PMJob 1 (supervisor)
\- job 2 (launch with exception handler)
\- job 3 (launch)
\- job 4 (launch)
When job 3 throws, job 2 cancels job 4 and propagates the exception up. Job 1 catches it and would not cancel any other children, but it doesn't have any anyway.bk9735732777
01/11/2025, 7:32 AM