publicfinaloverridefunresumeWith(result: Result<Any?>) { // This loop unrolls recursion in current.resumeWith(param) to make saner and shorter stack traces on resume var current = this var param = result while (true) { // Invoke "resume" debug probe on every resumed continuation, so that a debugging library infrastructure // can precisely track what part of suspended callstack was already resumed probeCoroutineResumed(current) with(current) { val completion = completion!! // fail fast when trying to resume continuation without completion val outcome: Result<Any?> = try { val outcome = invokeSuspend(param) if (outcome === COROUTINE_SUSPENDED) return Result.success(outcome) } catch (exception: Throwable) { Result.failure(exception) } releaseIntercepted() // this state machine instance is terminating if (completion is BaseContinuationImpl) { // unrolling recursion via loop current = completion param = outcome } else { // top-level completion reached -- invoke and return completion.resumeWith(outcome) return } } } }
其实这个函数做的事很简单,不停的循环并调用 current 指针的 invokeSuspend 函数来恢复协程的执行,如果返回 COROUTINE_SUSPEND 那就意味着又是暂停,返回;否则说明当前函数执行完了,从 current 指针指向的延续体中拿出它上一级的延续体,继续 invoke,直到回到根,结束退出。