android - 当 Android 应用程序终止时,Kotlin 协程不会停止
问题描述
看来我不像我想的那样理解 Kotlin 协程范围。我的印象是作用域结束时会自动取消协程。我启动了一个以“isActive”为条件的无限循环协程:
override fun onCreate(savedInstanceState: Bundle?)
{
GlobalScope.launch {
while (isActive)
{
log(this, object {}, "Hello GlobalScope", false)
delay(500)
}
}
...
由于它使用全局范围,我希望它在应用程序终止时停止,但在应用程序终止后它会继续运行:
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
I/BluetoothLeash: StandaloneCoroutine.invokeSuspend(): Hello GlobalScope
我有什么误解?
解决方案
如果你看一下 GlobalScope 的定义,你会发现它被声明为一个对象:
object GlobalScope : CoroutineScope { ... }
一个对象代表一个静态实例。所以它会在你的应用程序运行时消耗一些内存。即使你的应用程序被终止但进程没有被破坏,在 GlobalScope 中启动的协程可能仍在运行。
GlobalScope.launch(Dispatchers.IO): Launches a top-level coroutine on Dispatchers.Default. This coroutine is unbound and keeps running until the task is finished or cancelled
Use GlobalScope may be a bad idea because it is not bound to any job.
Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.
推荐阅读
- spring - Disadvantages to giving Spring Controller Session scope.
- javascript - Way to Open Clicked Link in New Tab via Tampermonkey?
- batch-file - 使用 cmd 一次重命名多个文件 [Windows 10]
- ruby - ruby dk.rb install:必须编辑配置文件
- angular - 超时更改时角度插值显示不更新
- delphi - 不同指针类型的不兼容类型
- spring - 使用复合键保存实体获取 ConversionNotSupportedException
- c++ - 如何跳过 ADO 中的失败行?
- excel - 使用perl在excel中编写时如何将精度设置为2?
- java - 使用 atan2() 在 Brick Breaker 游戏中查找对象的交点