Kotlin Coroutine GlobalScope 文档清晰度

Kotlin Coroutine GlobalScope documentation clarity

我很难理解 GlobalScope 的用法和文档。 文档指出:

A global CoroutineScope 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. Another use of the global scope is operators running in Dispatchers.Unconfined, which don’t have any job associated with them.

Application code usually should use an application-defined CoroutineScope. Using async or launch on the instance of GlobalScope is highly discouraged.

  1. GlobalScope 未绑定任何作业是什么意思?因为我可以

    val job = GlobalScope.launch {
        // some work
    }
    job.cancel() 
    
  2. 它说他们没有提前取消。这是什么意思?正如你在上面看到的,我可以取消它。

  3. 最后它说,它在整个应用程序生命周期内运行。因此,作用域会一直存在,直到应用程序终止。这与 CoroutineScope 相比如何?当我在 运行 CoroutineScope 中间退出 Android Activity 时,它仍然存在并运行直到完成。这是否意味着 CoroutineScope 完成后将通过垃圾收集进行清理,而 GlobalScope 不会?

link 到文档: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/

  1. What does it mean when GlobalScope is not bound to any job? Because I can do...

这是指缺少与 CoroutineScope 关联的 Job 对象,而不是“范围”内的单个协程 Job

  1. It says they are not canceled prematurely. What does this mean? As you can see above I can cancel it.

在任何时候调用 GlobalScope.cancel() 都会抛出 IllegalArgumentException

所以这会产生同样的错误:

fun main(args: Array<String>) {

    val myScope : CoroutineScope = object : CoroutineScope {
        override val coroutineContext: CoroutineContext = Dispatchers.IO // no job added i.e + SupervisorJob()
    }


    val job = myScope.launch { longRunningTask() }

    Thread.sleep(5_000)
    job.cancel() // this is fine - individual coroutine cancelled
    myScope.cancel() // this will throw an error, same as GlobalScope.cancel()
    
}
  1. Lastly it says, it operates on the whole application lifetime. So the scope stays alive until the application dies. How does this compare with CoroutineScope? When I exit an Android Activity in the middle of a running CoroutineScope, it'll still be alive and runs until completion. Does it just mean the CoroutineScope will get cleaned up w/ garbage collection after it completes and GlobalScope wont?

GlobalScope 是一个对象 class - 一个单例,因此持续时间与它运行的进程一样长。GlobalScope 实现 CoroutineScope 它只是一个预定义的范围图书馆自带。协程可以从 GlobalScope 启动,但调用者必须注意保留 Job 对象并通过 Job 取消每个协程。使用自定义 CoroutineScope 时,您可以更好地控制调用扩展函数 CoroutineScope.cancel() 时发生的情况 - 例如取消该范围内的所有子协程“运行”。

我在这个问题上没有权威,但这就是我解释文档和观察图书馆行为的方式。

老实说,我认为大多数人都难以简单明了地解释协程 - 大多数关于该主题的文章都不容易阅读,而且通常我会更加困惑。深入研究库源代码后,它通常会稍微消除一些东西,但您也可以看到它仍然处于持续开发的状态。