Kotlin:协程范围与协程上下文

编程入门 行业动态 更新时间:2024-10-24 05:15:59
本文介绍了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.它的关键作用是作为传递给launch,async等的块的隐式接收者.

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:协程范围与协程上下文

本文发布于:2023-11-23 10:03:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   Kotlin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!