调试Kotlin协程时如何逐步执行暂停功能调用

Dan*_*iel 5 debugging kotlin kotlin-coroutines

进入或退出“暂停”功能时,如何调试Kotlin代码?(请参见下面的示例)。

fun mainFunction() = runBlocking {

    println("before suspend call")

    anotherFunction()

    println("after suspend call")
}

suspend fun anotherFunction() {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

我知道Kotlin协同例程在执行暂挂函数时会发挥很多魔力,并且那一刻执行可能会切换线程。因此,当退出“ anotherFunction()”时,我只能遍历协程框架代码,而无法回到“ mainFunction()”。

但是,我想知道是否有可能像没有参与协程那样调试它。是否有启用此功能的工具或库?可能在共同例程支持的路线图上吗?

像禁用联合例程魔术的编译器标志这样简单的功能已经走了很长一段路,但是我什么也找不到。

我发现的唯一有用的东西是:-ea JVM参数还激活了kotlin调试模式,该模式将至少“修复”堆栈跟踪以查找异常。

Abh*_*kar 6

本页展示了一些通用技术。简而言之,使用启用的断言(-eaJVM 标志)运行。

kotlinx-coroutines-debug模块顾名思义是专门设计的。这就是我在单元测试中使用它的方式;

runBlocking {
    DebugProbes.install()
    val deferred = async { methodUnderTest() }
    delay(3000)
    DebugProbes.dumpCoroutines()
    println("\nDumping only deferred")
    DebugProbes.printJob(deferred)
    DebugProbes.uninstall()
    cleanup()
}
Run Code Online (Sandbox Code Playgroud)

JUnit4 规则可以减少样板文件,但您不应该在 2020 年底使用 JUnit4。

此外,Kotlin 1.4.0-RC 及更高版本支持从 IDE 内部调试协程,但就像 JetBrains 的所有新功能一样,我发现它还不成熟,并不总是显示挂起的协程;kotlinx-coroutines-debug效果更好。 https://blog.jetbrains.com/kotlin/2020/07/kotlin-1-4-rc-debugging-coroutines/

2020 年 10 月编辑:

我创建了一个 JUnit 5 扩展,可以在超时时转储协程。 https://github.com/asarkar/coroutines-test


Nao*_*dgi 1

-Dkotlinx.coroutines.debug虚拟机选项

该模块提供了一个调试 JVM 代理,允许跟踪和追踪现有的协程。

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-debug/