Kotlin Coroutine 的 block.startCoroutine() 是如何工作的?

问题描述 投票:0回答:1

我正在阅读KEEP中的协程提案。我在 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
是 Function Type
(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(...)
时,您实际上正在启动该块的执行。

尝试实现一个简单的函数类型扩展示例,但似乎不起作用。

谁能告诉我这个扩展函数类型是如何工作的?

编译器在暂停函数方面也发挥了任何作用吗?

kotlin kotlin-coroutines extension-methods
1个回答
0
投票

createCoroutineUnintercepted
suspendCoroutineUninterceptedOrReturn
都是Kotlin编译器识别和转换的特殊函数。它们是该语言提供的基本构建块,以便构建更多用户友好的框架(例如 Kotlinx 协程库)。

我推荐这篇博文来了解基本语言原语是什么以及我们如何利用它们构建像 Kotlinx 协程这样的框架: https://blog.kotlin-academy.com/kotlin-coroutines-animated-part-1-coroutine-hello-world-51797d8b9cd4

除了协程的 KEEP 之外,您可能会发现这个详细的技术文档也很有用: https://github.com/JetBrains/kotlin/blob/master/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/coroutines-codegen.md

© www.soinside.com 2019 - 2024. All rights reserved.