本文主要是介绍3.1-CoroutineScope/CoroutineContext:CoroutineScope 和 CoroutineContext 的概念,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- CoroutineContext 的概念
- CoroutineScope 的概念
在使用协程的时候我们会经常跟 CoroutineScope 和 CoroutineContext 打交道,但是对它们的之间有什么区别、概念是什么还是很模糊。在这里就把它们先讲清楚。
CoroutineContext 的概念
CoroutineContext 的概念其实顾名思义就是 协程的上下文,所有信息都是上下文,它们根据功能不同划分成了不同的分类,每个信息都是一个 CoroutineContext。比如管理流程用的是 Job,管理线程用的是 ContinuationInterceptor 等等。
CoroutineScope 的概念
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {// coroutineContext 属性保存了 launch {} 代码块的协程所有上下文信息val job = coroutineContext[Job]val job2 = coroutineContext.jobval continuationInterceptor = coroutineContext[ContinuationInterceptor]
}
在使用协程的时候我们经常会使用上面示例代码的方式获取上下文信息。
CoroutineScope 是一个 CoroutineContext 的容器,每一个协程都有它的一组的 CoroutineContext,这些 CoroutineContext 整合在一起被放进了 CoroutineContext 对象里面,最终以 CoroutineScope 的 coroutineContext 属性的形式存储了起来。
简单理解就是 CoroutineScope 有两个作用:
-
coroutineContext 属性保存它所对应的协程代码块的上下文信息
-
启动协程:创建协程是需要上下文信息的,通过 CoroutineScope 调用 launch 或 async 启动协程就可以拿它的 coroutineContext 属性来用
这篇关于3.1-CoroutineScope/CoroutineContext:CoroutineScope 和 CoroutineContext 的概念的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!