Android 应用程序终止时,Kotlin 协程不会停止

Kotlin coroutine not stopping when Android app terminates

看来我并不像我想的那样理解 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

使用 GlobalScope 可能不是一个好主意,因为它不绑定任何作业。

Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.

尝试使用lifecycleScope.launch { } 文档说:

  • 当 [Lifecycle] 被销毁时,该范围将被取消。