Kotlin:协程范围与协程上下文 [英] Kotlin: Coroutines scope vs Coroutine context

查看:119
本文介绍了Kotlin:协程范围与协程上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释他们之间的区别?我认为范围提供了一个引用(例如Job)来取消它们,上下文提供了对底层线程的引用.是这样吗?

Can anyone explain the difference between them? I think scope provides a reference(e.g. Job) to cancel them and context provides a reference to underlying thread. Is that so?

推荐答案

它们确实紧密相关.您可能会说CoroutineScope规范了CoroutineContext的继承方式.

They are indeed closely related. You might say that CoroutineScope formalizes the way the CoroutineContext is inherited.

CoroutineScope本身没有数据,它只保存一个CoroutineContext.它的关键作用是作为传递给launchasync等的块的隐式接收者.

CoroutineScope has no data on its own, it just holds a CoroutineContext. Its key role is as the implicit receiver of the block you pass to launch, async etc.

请参见以下示例:

runBlocking {
    val scope0 = this
    // scope0 is the top-level coroutine scope.
    scope0.launch {
        val scope1 = this
        // scope1 inherits its context from scope0. It replaces the Job field
        // with its own job, which is a child of the job in scope0.
        // It retains the Dispatcher field so the launched coroutine uses
        // the dispatcher created by runBlocking.
        scope1.launch {
            val scope2 = this
            // scope2 inherits from scope1
        }
    }
}

您可以看到CoroutineScope如何协调协程上下文的继承.如果您在scope1中取消作业,则该作业将传播到scope2,并且也将取消launch ed作业.

You can see how the CoroutineScope mediates the inheritance of coroutine contexts. If you cancel the job in scope1, this will propagate to scope2 and will cancel the launched job as well.

请注意关键的语法功能:我显式编写了scope0.launch,但是如果我只编写了launch,则暗含着完全相同的意思.这是CoroutineScope帮助自动"传播范围的方式.

Note the key syntactical feature: I explicitly wrote scope0.launch, but had I written just launch, it would implicitly mean exactly the same thing. This is how CoroutineScope helps to "automatically" propagate the scope.

这篇关于Kotlin:协程范围与协程上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆