Programming Kotlin: Difference between SupervisorJob() and supervisorScope (324, 325)

Hi @HarryDeveloper,

Thank you for the query.

The supervisorScope is a syntax sugar or a convenience function for creating a SupervisorJob. If the child coroutines run in a different SupervisorJob than the parent, then the cancellation of a Chile does not propagate to the parent.

It is much better to use supervisorScope than to use SupervisorJob, but from the curiosity point of view, you may try to create a SupervisorJob, something like this:

val job = launch(Dispatchers.IO + SupervisorJob() + handler) {

val supervisor = SupervisorJob()

launch(coroutineContext + supervisor) { fetchResponse(200, 5000) }
launch(coroutineContext + supervisor) { fetchResponse(200, 1000) }
launch(coroutineContext + supervisor) { fetchResponse(200, 3000) }

supervisor.children.forEach { it. join() }

/*
supervisorScope {
  launch { fetchResponse(200, 5000) }
  launch { fetchResponse(200, 1000) }
  launch { fetchResponse(200, 3000) }
}
*/

}

job.join()

Hope that answers your question.

Regards,

Venkat