I have a scope with two child coroutines inside it
If one of the child "crasches" or throw an exception i want the another child to continue execution
suspend fun main() {
val context = Dispatchers.Default + SupervisorJob()
val scope = CoroutineScope(context = context)
val job = scope.launch {
launch() {
repeat(25) {
println("child 1 $it")
delay(25)
}
}
launch {
repeat(20) {
println("child 2 $it")
delay(18)
if (it == 16)
throw Exception("aaa")
}
}
}
job.join()
println("Main finished")
}
What i want to achieve is that if child two throws en exception, i want child one to continue until it finishes is job.
>Solution :
Wrap the children in a supervisorScope:
suspend fun main() {
val context = Dispatchers.Default + SupervisorJob()
val scope = CoroutineScope(context = context)
val job = scope.launch {
supervisorScope {
launch {
repeat(25) {
println("child 1 $it")
delay(25)
}
}
launch {
repeat(20) {
println("child 2 $it")
delay(18)
if (it == 16)
throw Exception("aaa")
}
}
}
}
job.join()
println("Main finished")
}
Another option is to use an external scope that uses a SupervisorJob to run the other coroutines, but then they are no longer children of this coroutine. You need to join them manually since they are not children. So usually this is not the way you want to do it.
suspend fun main() {
val context = Dispatchers.Default + SupervisorJob()
val scope = CoroutineScope(context = context)
val job = scope.launch {
val job1 = scope.launch {
repeat(25) {
println("child 1 $it")
delay(25)
}
}
val job2 = scope.launch {
repeat(20) {
println("child 2 $it")
delay(18)
if (it == 16)
throw Exception("aaa")
}
}
job1.join()
job2.join()
}
job.join()
println("Main finished")
}