首页 > 解决方案 > 如何在 Kotlin 中获取协程的名称?

问题描述

我很好奇协程suspended在主线程上的内部工作。真正的问题是如何suspended在主线程上记录一个协程函数。执行的具体地点在哪里?是虚拟线程吗?

标签: androidkotlincoroutine

解决方案


如果您正在谈论记录协程名称:

你可以通过

  1. 给协程命名(如果你想要自定义名称):launch(CoroutineName("My-Coroutine"))

  2. 在 IntelliJ 工具栏菜单中启用日志记录:运行 -> 编辑配置并添加

-Dkotlinx.coroutines.debug在虚拟机选项中。

编辑配置中的 VM 选项

然后你可以@My-Coroutine在logcat中看到。

在编辑配置更改后尝试以下代码:

fun main() = runBlocking {
println("   'runBlocking': I'm working in thread ${Thread.currentThread().name}")

val job = launch(CoroutineName("my-custom-name")) {
    println("   'runBlocking': I'm working in thread ${Thread.currentThread().name}")

}

job.join()}

结果: 结果


推荐阅读