Kotlin CoroutineScope 初始化取决于带有自定义 getter 的 CoroutineContext

Kotlin CoroutineScope initialization depending upon CoroutineContext with custom getter

google 代码实验室 Android 看得见风景的房间 - Kotlin 具有以下 snippet

class WordViewModel(application: Application) : AndroidViewModel(application) {

    // ...

    private val coroutineContext: CoroutineContext
       get() = parentJob + Dispatchers.Main

    private val scope = CoroutineScope(coroutineContext)

    // ...

}

根据我从 回答中了解到的情况,自定义 getter 每次都会被评估,而赋值仅在构建时评估。所以实际上,scope 会取一个以后不会改变的值,那么 coroutineContext 的自定义 getter 有什么用?

我认为在这个例子中我们可以去掉

private val coroutineContext: CoroutineContext
   get() = parentJob + Dispatchers.Main

然后写

private val scope = CoroutineScope(parentJob + Dispatchers.Main)

因此结果代码将如下所示:

class WordViewModel(application: Application) : AndroidViewModel(application) {
    private var parentJob = Job()
    private val scope = CoroutineScope(parentJob + Dispatchers.Main)
    // ...
}

我想在这种情况下写 getter 是一种风格问题。如果我们删除它,什么都不会改变。

当您在具有生命周期的组件中定义 CoroutineScope 时,将 coroutineContext 定义为计算 属性(或自定义 getter)更有意义(即Android Activity)。 Javadoc 中的示例不言自明:

class MyActivity : AppCompatActivity(), CoroutineScope {
    lateinit var job: Job
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        job = Job()
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel() // Cancel job on activity destroy. After destroy all children jobs will be cancelled automatically
    }
}

在这种情况下,您将在生命周期方法中创建 Job,这就是为什么您需要计算 属性 到 return coroutineContextJob 实例创建于 onCreate.