以协程delay函数为例子,suspendCancellableCoroutine传进去一个回调,接收回调的参数是cont:CancellableContinuation<Unit>
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
// if timeMillis == Long.MAX_VALUE then just wait forever like awaitCancellation, don't schedule.
if (timeMillis < Long.MAX_VALUE) {
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
}
来到内部,是 suspendCoroutineUninterceptedOrReturn再传一个回调进去,接收参数是uncont: Continuation,这里回调是利用参数uncont,创建CancellableContinuationImpl,并初始化,然后调上一层传递进来的block回调,把CancellableContinuation传递给block,其实也就是这个 if (timeMillis < Long.MAX_VALUE) { cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont) } 最后拿结果 getResult
public suspend inline fun <T> suspendCancellableCoroutine(
crossinline block: (CancellableContinuation<T>) -> Unit
): T =
suspendCoroutineUninterceptedOrReturn { uCont ->
val cancellable = CancellableContinuationImpl(uCont.intercepted(), resumeMode = MODE_CANCELLABLE)
/*
* For non-atomic cancellation we setup parent-child relationship immediately
* in case when `block` blocks the current thread (e.g. Rx2 with trampoline scheduler), but
* properly supports cancellation.
*/
cancellable.initCancellability()
block(cancellable)
cancellable.getResult()
}
最底层会调用到下面的这个玩意。suspendCoroutineUninterceptedOrReturn,参数也是个回调
block: (Continuation<T>) -> Any?
public suspend inline fun <T> suspendCoroutineUninterceptedOrReturn(crossinline block: (Continuation<T>) -> Any?): T {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
throw NotImplementedError("Implementation of suspendCoroutineUninterceptedOrReturn is intrinsic")
}
contract是契约的意思,意思是告诉编译器这是会执行一次block函数。
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
kotlin编译器如下方法,在编译时会把contract契约声明解析成生成 block.invoke(continuation) 字节码调用,内联插入调用的地方, kotlin使用了asm对字节码进行了非常精细的指令插入。
kotlin编译器用ASM一通操作,输出最终字码,反编译最终字节码,比原有的方法多了一个Continuation $completion参数,这玩意就是编译器干的活,根据上面的契约声明,把block函数内联调用优化到一个函数去,输出的字节码结果如下:
kotlinx.coroutines.DelayKt;
@Nullable
public static final Object delay(long timeMillis, @NotNull Continuation $completion) {
if (timeMillis <= 0L) {
return Unit.INSTANCE;
} else {
int $i$f$suspendCancellableCoroutine = false;
int var5 = false;
CancellableContinuationImpl cancellable$iv = new CancellableContinuationImpl(IntrinsicsKt.intercepted($completion), 1);
cancellable$iv.initCancellability();
CancellableContinuation cont = (CancellableContinuation)cancellable$iv;
int var8 = false;
if (timeMillis < Long.MAX_VALUE) {
getDelay(cont.getContext()).scheduleResumeAfterDelay(timeMillis, cont);
}
Object var10000 = cancellable$iv.getResult();
if (var10000 == IntrinsicsKt.getCOROUTINE_SUSPENDED()) {
DebugProbesKt.probeCoroutineSuspended($completion);
}
return var10000 == IntrinsicsKt.getCOROUTINE_SUSPENDED() ? var10000 : Unit.INSTANCE;
}
}
总结:就是kotlin编译器使用ASM进行字节码修改,内联优化,非常灵活,有兴趣可以去了解kotlin的编译器,都是开源的。