https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

Prateek Kumar

02/27/2024, 6:01 PM
Why is the Job passed to context of launch not respected? Approach 1:-
Copy code
viewModelScope.launch(coroutineExceptionHandler) {
    supervisorScope {
        for (i in 0..10) {
            launch {
                delay(i * 1000L)
                throw RuntimeException("abc")
            }
        }
    }
}
Here in Exception Handler all 10 exceptions are recorded. Approach 2:-
Copy code
viewModelScope.launch(coroutineExceptionHandler+ SupervisorJob()) {
    for (i in 0..10) {
        launch {
            delay(i * 1000L)
            throw RuntimeException("def")
        }
    }
}
With this only one exception is recorded and rest are cancelled after first exception. Why is 1 and 2 works differently? Shouldn’t the parent Job used to create child jobs?
s

Sam

02/27/2024, 7:33 PM
launch
always creates a new job as the child of the job in its starting context. Passing a job as an argument to the launch function merely replaces its parent job, and is rarely if ever a useful thing to do.
☝️ 1
p

Prateek Kumar

02/28/2024, 4:25 AM
If that is the case then a nested launch should override SuperviserJob and just be a normal Job,Right?
_viewModelScope_._launch_(coroutineExceptionHandler) *{*
supervisorScope *{*
for (i in 0..10) {
_launch_ *{*
delay(i * 1000L)
_launch_ *{*
//This scope should not be Supervisor Job but it is
throw RuntimeException("def")
}
}
}
}
}
Above code still collects all the exceptions even though the launch throwing the exception is not directly part of supervisorScope
2 Views