abstract class ScopedAppActivity: AppCompatActivity(), CoroutineScope {
protected lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
launch(Dispatchers.Main) {
try {
delay(Long.MAX_VALUE)
} catch (e: Exception) {
// e will be a JobCancellationException if the activty is destroyed
}
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
This example is copied from the coroutine guide and extended by the launch(Dispatchers.Main) coroutine. I don't understand why + Dispatchers.Main in line 4 is needed. If I remove this part the launch coroutine will be cancelled anyways if the Activity is destroyed. So what is the reason for Dispatchers.Main? Why is Dispatchers.IO not added, too?