我目前正在学习协程。在我的onCreate
类的Application
中,我执行了以下操作:
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")
}
}
我希望onCreate
完成后会取消该作业,但它会无限运行: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
CoroutineScope
的范围是什么?到达onCreate
的结尾后,是否应该立即取消它? job
是局部变量,因此会被垃圾回收? 最佳答案
如果线程仍在运行,则无法对其进行垃圾回收。
协程仍在运行,并且onCreate()结束时不会被取消。如果要在销毁碎片或 Activity 时自动取消协程,可以将协程附加到碎片或 Activity 的生命周期。但是,onCreate()和函数通常没有生命周期。如果要实现类似的目的,则必须在函数末尾添加job.cancel()
。
因此,回答您的问题:
关于android - CoroutineScope的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62623946/