作用域函数和。协程中的作用域

Scope functions vs. scopes in Coroutines

Kotlin 自带 scope functions and coroutines also have scopes。这两个范围是相关的还是只是命名相同以混淆新手?

TL;DR

Scope functions refer to scope in terms of variable scopingCoroutine scopes refer to scopes in terms of structured concurrency。 所以范围函数与协程范围和 vice-versa.

无关

完整答案:

Scope 是计算机科学中的一个超载术语。

Scope functions refer to scope in terms of variable scoping 即:

val result = run {
   val x = 1
   val y = 2
   // x and y variables are visible here
   x + y
}
println(x) // compile-time error, variable x is not known here

Coroutine scopes refer to scopes in terms of structured concurrency。在这个意义上,scope 定义了您启动的协程可以存活多长时间。 您可以在全局范围内启动协程:

val globalJob = GlobalScope.launch {
   // do some fancy work here
}

它一直执行到:

  • 您手动完成作业(globalJob.join()globalJob.cancel()
  • launch lambda 内部的工作完成
  • 申请过程结束——即GlobalScope结束

但是,您应用的某些组件的生命周期可能比整个应用的生命周期短。因此你可以使用例如。 ViewModelScope 与 Android ViewModel 一样长。当组件 (ViewModel) 的生命周期以及绑定到它的范围结束时,在该范围内启动的所有协程都会自动取消。

现在您可以看到一些相似之处,这些相似之处解释了为什么在两种情况下都使用相同的术语 - scope

范围 通常定义事物的寿命。

所以全局变量在某种程度上类似于在 GlobalScope 中启动的协程。

然而,这种相似性仅在概念层面 - 技术上可变作用域与协程作用域完全不同。

PS

Scope 一词也用于一些 DI 框架(有时称为 container),但是本主题 不在这个答案的范围 :)