Kotlin Sequence中yield函数的协程恢复位置探究
我认为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

