我读的是KEEP的Coroutine proposal.我在Coroutine Builders区偶然发现了这段代码.
fun launch(context: CoroutineContext = EmptyCoroutineContext, block: suspend () -> Unit) =
block.startCoroutine(Continuation(context) { result ->
result.onFailure { exception ->
val currentThread = Thread.currentThread()
currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception)
}
})
并且startCoroutine
是函数类型(suspend () -> T)
的扩展函数
**
* Starts a coroutine without a receiver and with result type [T].
* This function creates and starts a new, fresh instance of suspendable computation every time it is invoked.
* The [completion] continuation is invoked when the coroutine completes with a result or an exception.
*/
@SinceKotlin("1.3")
@Suppress("UNCHECKED_CAST")
public fun <T> (suspend () -> T).startCoroutine(
completion: Continuation<T>
) {
createCoroutineUnintercepted(completion).intercepted().resume(Unit)
}
我想知道startCoroutine()
函数如何执行它正在扩展的函数block
.因为我在代码中看不到任何this()
.
createCoroutineUnintercepted()
还扩展了相同的函数类型,但那里没有源代码实现.
@SinceKotlin("1.3")
public expect fun <T> (suspend () -> T).createCoroutineUnintercepted(
completion: Continuation<T>
): Continuation<Unit>
询问ChatGPT没有带来任何答案.它说
当您调用
block.startCoroutine(...)
时,您实际上是在启动块的执行.
try 实现一个简单的函数类型扩展example,但似乎不起作用.
有谁能告诉我这个扩展函数类型是如何工作的吗?
编译器在挂起这方面的函数时也会施展什么魔力吗?