Kotlin 协程三类 Continuation

协程主要有三类 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)
                }
            }
        }
    }

在这里插入图片描述

参考:https://www.jianshu.com/p/2979732fb6fb

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值