🔄 Deferred.await() 完整调用流程图
👤 用户调用 Deferred.await()
↓
🔍 DeferredCoroutine.await() → 检查 getCompleted() 状态
↓
❓ 完成状态判断
├── ✅ 已完成 → getCompleted() 直接返回结果
│ ├── CompletedExceptionally → throw state.cause
│ └── 正常完成 → return result (直接返回)
│
└── ⏳ 未完成 → awaitSuspend() 挂起等待
↓
🔗 suspendCancellableCoroutine {
cont -> ... }
↓
📝 invokeOnCompletion(onCancelling = false) {
cause -> ... }
↓
🔄 loopOnState {
state -> ... } 状态循环检查
↓
❓ 当前状态判断
├── 🏃 Incomplete → makeNode() 创建回调节点
│ ↓
│ 🔒 _state.compareAndSet(state, state + node) 原子添加
│ ↓
│ 📦 return node (JobNode) 作为 DisposableHandle
│
└── ✅ 已完成 → invokeIt(handler, state) 立即执行回调
↓
📞 handler(cause) 执行用户回调
↓
🎯 提取结果:getCompleted() 获取实际值
↓
🎯 cont.resume(result) 或 cont.resumeWithException(cause)
↓
⏸️ cancellable.getResult() → COROUTINE_SUSPENDED 挂起标记
↓
🕐 等待目标协程完成...
↓
🎯 目标协程完成:AbstractCoroutine.resumeWith(result)
↓
📍 makeCompletingOnce(result.toState())
↓
🔄 loopOnState {
state -> ... } 完成状态转换
↓
🔧 Completing(state.list, false, proposedUpdate) 创建完成状态
↓
🔒 _state.compareAndSet(state, completing) 原子更新状态
↓
📢 completeStateFinalization(state, completing)
↓
🔔 notifyCompletion(list, cause) 通知所有回调
↓
🔄 list.forEach<JobNode<*>> {
node -> node.invoke(cause) }
↓
🎯 AwaitContinuation.invoke() → handler(cause) 执行await的回调
↓
📦 val result = getCompleted() 获取实际结果值
↓
📞 CancellableContinuationImpl.resumeWith(Result.success(result))
↓
🔒 tryResumeImpl() → _state.compareAndSet(ACTIVE, result)
↓
🚀 dispatchResume(resumeMode) 派发恢复
↓
🧵 CoroutineDispatcher.dispatch(context, this)
↓
🎯 目标线程执行 DispatchedTask.run()
↓
📞 continuation.resumeWith(Result.success(result))
↓
🔄 BaseContinuationImpl.resumeWith() 状态机恢复
↓
⚙️ 状态机.invokeSuspend() 继续执行用户代码
↓
🏁 await() 方法返回实际结果值,用户代码继续执行
🎯 核心源码方法明确讲解
1. 🔍 DeferredCoroutine.await() - 入口方法
public final override suspend fun await(): T {
val state = this.state
if (state !is Incomplete) {
if (state is CompletedExceptionally) {
throw state.cause
}
return state as T
}
<