构造CoroutineScope使用到的CoroutineContext是一个特殊的集合,这个集合它既有Map的特点,也有Set的特点,集合的每一个元素都是Element,每个Element都有一个Key与之对应,对于相同Key的Element是不可以重复存在的,Element之间可以通过+号组合起来,后面我会详细介绍CoroutineContext这个特殊集合的结构,接下来我先简单讲解一下组成...
public interface CoroutineScope { public val coroutineContext: CoroutineContext } 1. 2. 3. 4. 由上面CoroutineScope 源码可以看出,它只包含唯一的元素CoroutineContext,所以它只是对 CoroutineContext 做了一层封装而已,它的核心能力其实都来自于 CoroutineContext。 下面是一个使用 CoroutineScope 使用并管理协程的...
* Returns a context containing elements from this context and elements from other [context]. * The elements from this context with the same key as in the other one are dropped. */ public operator fun plus(context: CoroutineContext): CoroutineContext = ... /** * Returns a context containin...
本文主要介绍了CoroutineContext的元素组成和结构,理解CoroutineContext对于理解协程使用有很大的帮助,因为协程的启动时就离不开CoroutineContext,同时如果你以后想要更深入的学习协程,例如协程的创建过程,Continuation概念、suspend关键字等,本篇文章也能给你一个抛砖引玉的效果。
创建一个 Job 实例val job:Job=Job()// 将 Job 实例作为 CoroutineContext.Elementval jobElement:CoroutineContext.Element=job// 使用 jobElement 创建一个 CoroutineContextval jobContext:CoroutineContext=jobElement// 使用 name 和 job 实例创建一个新的 CoroutineContext 实例 ctxval ctx:CoroutineContext=name+...
Persistent context for the coroutine. It is an indexed set of [Element] instances. An indexed set is a mix between a set and a map. Every element in this set has a unique [Key]. CoroutineContext是协程的上下文。 CoroutineContext是element的set集合,没有重复类型的element对象。
CoroutineScope 的取消也表示着在此作用域内开启的协程将会被全部取消. CoroutineScope 内还可以创建 子CoroutineScope , 不同类型的作用域作用域代表着在此作用域内协程最大运行的时间不同。 例如 GlobalScope 表示协程的最大可运行时间为整个APP的运行生命周期,Activity CoroutineScop...
CoroutineExceptionHandler 挂起函数可以访问协程上下文 小结 17 | Context:万物皆有 Context 从概念上讲,CoroutineContext 只是个上下文而已,开发中最常见的用处就是切换线程池,但其背后的代码设计其实比较复杂,Kotlin 协程中比较重要的概念,都或多或少跟 CoroutineContext 有关系。
CoroutineContext 协程的上下文,它包含用户定义的一些数据集合,这些数据与协程密切相关。它类似于集合,可以通过来获取不同类型的数据。同时的灵活性很强,如果其需要改变只需使用当前的来创建一个新的即可。 来看下的定义 每一个都有它唯一的一个其中的类型是,我们可以通过对应的来获取对应的具体对象。说的有点抽象我...
我们知道,通过CoroutineScope.launch方法可以启动一个协程。该方法第一个参数的类型就是CoroutineContext。默认值是EmptyCoroutineContext单例对象。 在开始讲解CoroutineContext之前我们来看一段协程中经常会遇到的代码 刚开始学协程的时候,我们经常会和Dispatchers.Main、Job、CoroutineName、CoroutineExceptionHandler打交道...