首页 > 解决方案 > 当 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

我有什么误解?

标签: androidkotlin-coroutines

解决方案


如果你看一下 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.


推荐阅读