I am currently learning about coroutines. In onCreate of my Application class I did the following:
override fun onCreate() {
super.onCreate()
val job = CoroutineScope(IO).launch {
while(true) {
Timber.i("hello from coroutine")
delay(1000)
}
}
job.invokeOnCompletion {
Timber.i("job.invokeOnCompletion")
}
}
I would have expected the job to be canceled once onCreate is finished, but instead it runs endlessly:
2020-06-28 16:23:11.436 onCreate$job: hello from coroutine
[..]
2020-06-28 16:23:19.489 onCreate$job: hello from coroutine
2020-06-28 16:23:21.504 onCreate$job: hello from coroutine
2020-06-28 16:23:22.512 onCreate$job: hello from coroutine
2020-06-28 16:23:23.516 onCreate$job: hello from coroutine
[..]
2020-06-28 16:23:45.671 onCreate$job: hello from coroutine
- So what is the scope of
CoroutineScope? Shouldn't it be canceled as soon as the end ofonCreateis reached? - Notice the job output, there's a gap between 16:23:19.489 and 16:23:21.504, missing 16:23:20. Can anyone explain why?
- I forced a garbage collection multiple times, still the output continues. Would have expected the
jobto be garbage collected as it is a local variable?