我把 RunSuspend.kt 的内容拷贝到我自己的文件中:
@SinceKotlin("1.3")
internal fun runSuspend(block: suspend () -> Unit) {
val run = RunSuspend()
block.startCoroutine(run)
run.await()
}
private class RunSuspend : Continuation<Unit> {
override val context: CoroutineContext
get() = EmptyCoroutineContext
var result: Result<Unit>? = null
override fun resumeWith(result: Result<Unit>) = synchronized(this) {
this.result = result
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (this as Object).notifyAll()
}
fun await() = synchronized(this) {
while (true) {
when (val result = this.result) {
null -> @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (this as Object).wait()
else -> {
result.getOrThrow() // throw up failure
return
}
}
}
}
}
然后反编译:
public final class RunSuspend1Kt {
@SinceKotlin(
version = "1.3"
)
public static final void runSuspend(@NotNull Function1 block) {
Intrinsics.checkParameterIsNotNull(block, "block");
RunSuspend run = new RunSuspend();
ContinuationKt.startCoroutine(block, (Continuation)run);
run.await();
}
}
发现 runSuspend 的参数变成了一个 Function1 实例了;
但是在 kotlin 里面是一个 block: suspend () -> Unit
我在跟踪 suspend main 的时候也发现这个问题了,这是为什么呢?为啥不是一个 Continuation 呢???