You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Sequence中yield函数的协程恢复位置探究

Kotlin Sequence的协程本质与恢复逻辑解析

我认为Kotlin的Sequence本质是一个带有yield挂起函数的协程——这个理解完全正确。yield函数会设置当前要返回的元素值并挂起协程,直到下一次请求序列元素时才会恢复执行。

yield函数源码

override suspend fun yield(value: T) {
    nextValue = value
    state = State_Ready
    return suspendCoroutineUninterceptedOrReturn { c ->
        nextStep = c
        COROUTINE_SUSPENDED
    }
}

从这段源码能看到,yield会先把要返回的元素赋值给nextValue,将序列状态置为State_Ready,然后通过suspendCoroutineUninterceptedOrReturn挂起协程,同时把当前协程的Continuation对象存储到nextStep变量中,等待后续触发恢复。


问题:这个协程的恢复操作是在哪里执行的?

你提到在next()方法里没找到resume调用,先看next()的源码:

override fun next(): T {
    when (state) {
        State_NotReady, State_ManyNotReady -> return nextNotReady()
        State_ManyReady -> {
            state = State_ManyNotReady
            return nextIterator!!.next()
        }
        State_Ready -> {
            state = State_NotReady
            @Suppress("UNCHECKED_CAST")
            val result = nextValue as T
            nextValue = null
            return result
        }
        else -> throw exceptionalState()
    }
}

协程恢复的核心位置:nextNotReady()方法

协程的恢复逻辑其实藏在next()调用的nextNotReady()方法里。当Sequence处于State_NotReady或State_ManyNotReady状态(也就是没有预先生成好的元素)时,next()会调用nextNotReady(),这个方法内部会完成协程的恢复操作。

nextNotReady()的核心逻辑简化后如下:

private fun nextNotReady(): T {
    while (true) {
        val step = nextStep ?: throw NoSuchElementException()
        nextStep = null
        step.resume(Unit) // 这里就是恢复协程的关键代码
        when (state) {
            State_Ready -> return nextValue as T
            State_Done -> throw NoSuchElementException()
            // 处理其他中间状态
        }
    }
}

逻辑说明

当调用next()且当前没有可用元素时,nextNotReady()会取出之前存在nextStep中的Continuation对象,调用它的resume(Unit)方法,让之前被yield挂起的协程从挂起点继续执行。协程恢复后会继续运行到下一个yield语句(或者序列执行结束),生成新的元素并设置nextValue和状态,随后再次挂起,等待下一次next()调用触发新一轮的恢复流程。

简单来说:Sequence的协程恢复不是直接在next()方法中,而是通过next()调用的nextNotReady()方法,利用Continuation的resume完成协程的恢复。


内容的提问来源于stack exchange,提问作者Vencat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:40:25