协程主要有三类 Continuation,通过代理模式将协程的各层包装组合在一起,每类负责不同的功能。
第一层 Continuation 是 CoroutineScope.launch() 和 CoroutineScope.async() 方法分别返回的 Job、Deferred,里面封装了协程状态,提供了取消协程的接口,它们所属的类(StandaloneCoroutine、DeferredCoroutine)都是继承自 AbstractCoroutine,而 AbstractCoroutine 实现了 Continuation 接口。职责是使用指定的结果完成协程的执行。
/**
* Completes execution of this with coroutine with the specified result.
*/
public final override fun resumeWith(result: Result<T>) {
val state = makeCompletingOnce(result.toState())
if (state === COMPLETING_WAITING_CHILDREN) return
afterResume(state)
}
第二类 Continuation 是编译器生成的 SuspendLambda (suspend lambda) 和 ContinuationImpl (suspend fun) 的子类,职责是封装协程的真正的运算逻辑(invokeSuspend() 方法),继承自 BaseContinuationImpl,其 completion 属性是协程的第一类 Continuation 或者上一层的第二类 Continuation。
第三类 Continuation 是协程线程调度时用到的 DispatchedContinuation,职责是封装线程调度逻辑(dispatcher 属性),其包含了协程的第二类 Continuation (continuation 属性)。
override fun resumeWith(result: Result<T>) {
val context = continuation.context
val state = result.toState()
if (dispatcher.isDispatchNeeded(context)) {
_state = state
resumeMode = MODE_ATOMIC
dispatcher.dispatch(context, this)
} else {
executeUnconfined(state, MODE_ATOMIC) {
withCoroutineContext(this.context, countOrElement) {
continuation.resumeWith(result)
}
}
}
}