在 IntelliJ IDEA 中调试 Kotlin 协程与 Flow

在 IntelliJ IDEA 中调试 Kotlin 协程与 Flow

原文:Kotlin 官方的 协程调试教程(页面标注2025-03-10)与 Flow调试教程(页面标注2026-06-16)。两篇都使用 kotlinx-coroutines-core:1.11.0 示例版本。作者归属为 Kotlin Documentation Team;两个页面来源、代码版本和图像来源分别列明。

版本提醒:原文 Gradle 依赖示例为 kotlinx-coroutines-core:1.11.0;依赖、IDE和编译器行为会变化。原教程建议使用 -Xdebug 的说明早于当前 Kotlin 编译器 API 2.2 的实现变化:官方编译器源码说明,API 2.2 及以上通过 SpillingKt.nullOutSpilledVariable 处理死变量,调试器可替换其返回行为;-Xdebug 仅影响 API 2.2 以下的旧路径,并会停用引用清理,可能造成内存泄漏。不要把它当作现代项目修复或生产参数;先核对项目实际 compiler API 版本。

IntelliJ IDEA Coroutine 调试器状态示意:runBlocking等待两个async子任务,逐次Resume后a和b依次运行并完成;协程视图展示RUNNING、SUSPENDED、CREATED状态。
依据 Kotlin 原文教程中的协程状态变化重新绘制;不是IDE截图或执行记录。

本教程演示如何创建 Kotlin 协程并使用 IntelliJ IDEA 调试,读者需要先了解协程的基本概念。

准备协程示例

  1. 在 IntelliJ IDEA 打开 Kotlin 项目;如果尚无项目,先创建 Kotlin 项目。
  2. Gradle 项目通过依赖声明加入 kotlinx.coroutines。原文使用版本 1.11.0,Kotlin DSL 写法如下;Groovy DSL 见代码后的说明。
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

Groovy DSL 相应写法为 implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0'。其他构建工具按 kotlinx.coroutines README 的安装说明配置。

  1. 打开 src/main/kotlin 下的 Main.kt。新建项目的示例通常已有 main 函数。
  2. 把 main 函数改成包含一个 runBlocking 协程作用域,并启动两个用来计算结果的 async 子协程:
import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    val a = async {
        println("我正在计算答案的一部分")
        6
    }
    val b = async {
        println("我正在计算答案的另一部分")
        7
    }
    println("结果是 ${a.await() * b.await()}")
}

runBlocking 让 main 函数等待作用域中的协程完成;async 返回 Deferred 值,await 等待子协程结果。构建项目,确认IDE已成功编译代码,再运行调试。

后续 Flow 小节来自另一篇相邻的官方调试教程;它从 simple() 冷流的发送/收集开始,再用 buffer() 展示生产者与消费者分离。两个教程合并后覆盖协程与 Flow 两条主线。

观察协程调试状态

  1. 在两条 println 所在行设置断点。
  2. 通过顶部运行配置旁的 Debug 操作以调试模式启动。Debug 工具窗口打开后,Frames 显示调用帧,Variables 显示当前协程上下文变量,Coroutines 标签页则列出正在运行或挂起的协程。

在原文的示例中,Coroutines 视图此时显示三个协程:外层 runBlocking 是 RUNNING,两个 async 子协程尚为 CREATED。这里的“创建”表示子任务已建立,但尚未在断点处运行;具体呈现取决于调试位置及调度时机。

点 Resume Program 继续执行后,外层协程会等待需要的 Deferred 结果,视图中第一个协程呈 SUSPENDED;其中一个子协程正在计算值 a,状态为 RUNNING;另一个子协程仍是 CREATED,还没有计算 b。再次 Resume,a 的计算完成并从活动协程视图消失,b 接着运行。两个值到齐后,外层协程可以继续执行乘法并输出 42。

这项视图让调试者查看多个协程的状态,而不是把所有行为压成一个普通的线程调用栈。线程与协程不是一一对应关系,协程切换调度器时仍需结合 CoroutineContext、调用帧和变量面板理解现场。

“was optimized out” 表示什么

在 suspend 函数中,调试器可能在某些变量旁显示 was optimized out。这表示变量的生命周期已经结束,它在当前状态下不再存在,所以调试器无法显示其值;这会让协程调试更困难。

原教程写道,可以用 -Xdebug 禁用此行为。该建议只对应 API 版本低于 2.2 的旧编译器路径:启用后编译器不清理死变量引用,因此官方警告它可能造成内存泄漏,绝不可用于生产。对于 API 2.2 及以上,死变量清零改由 kotlin.coroutines.jvm.internal.SpillingKt.nullOutSpilledVariable 执行,调试器可在调试时替换其实现;-Xdebug 不再是解决当前优化变量可见性的通用手段。可对照 Kotlin 编译器的协程实现说明(滚动 master 源码,核对日期2026-10-08)。

用 Flow 调试发送、收集与 buffer

Flow 示例用慢速发射器与慢速收集器,观察同一协程内的挂起点。这里的 delay 模拟等待时间,会挂起协程但不阻塞线程;它不是 CPU 密集型计算的替代品。

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun simple(): Flow<Int> = flow {
    for (i in 1..3) {
        delay(100)
        emit(i)
    }
}

fun main() = runBlocking {
    simple().collect { value ->
        delay(300)
        println(value)
    }
}

在 emit(i) 处设断点并以 Debug 运行;Frames 查看调用栈,Variables 查看当前值,Coroutines 列出运行或挂起的协程。原教程展示了 Flow 按顺序发射三个数字,并在 println(value) 处逐步暂停。这里的屏幕状态来自官方教程,而非本稿运行。

要让发射与收集并发,给流加上 buffer()。它在两者之间缓存已发射值,并运行一个独立协程承接发射端:

fun main() = runBlocking<Unit> {
    simple()
        .buffer()
        .collect { value ->
            delay(300)
            println(value)
        }
}

在 println(value) 处观察调试器:一帧中发射器为 RUNNING、收集器为 SUSPENDED;继续执行后,两者状态交换。断点会改变调度时序,示例状态不能外推为生产系统的精确时序。

官方 IntelliJ IDEA 调试器截图:buffer后的 Coroutine 1 为 SUSPENDED,Coroutine 2 正在 main 线程运行;Variables面板显示 i=1
官方 Flow 调试教程的缓冲后协程状态之一:发射器运行、收集器挂起。图源 Kotlin Flow 调试教程,不是本稿运行记录。
官方 IntelliJ IDEA 调试器截图:继续执行后 Coroutine 1 正在运行,Coroutine 2 为 SUSPENDED
继续执行后的另一状态:收集器运行、发射器挂起。图源同上;断点位置及调度会影响观察结果。

安全与代码审查:样例只启动计算整数的内存内协程,没有访问网络、磁盘或秘密。依赖版本和示例均为静态审读;没有在 IntelliJ 中构建或执行代码,因此本文不宣称调试器效果已实测。应使用项目锁定且官方支持的协程库版本。

作者与来源分别为:Kotlin Documentation Team 的 协程调试教程,以及 Flow 调试教程。Flow 页面编辑入口指向官方 kotlinx.coroutines 仓库;本文所用 Flow 代码片段与两张Flow调试截图按该仓库 Apache License 2.0 及 NOTICE 保留版权和许可文本。协程教程的公开页面未显示独立许可证声明,其中文译写依据另行授权制作;不把 Flow 仓库许可扩张解释为第一篇页面的许可。

Apache License 2.0(完整文本)

展开 Apache License 2.0
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2000-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

NOTICE(完整原文)

=========================================================================
==  NOTICE file corresponding to the section 4 d of                    ==
==  the Apache License, Version 2.0,                                   ==
==  in this case for the kotlinx.coroutines library.                   ==
=========================================================================

kotlinx.coroutines library.
Copyright 2016-2025 JetBrains s.r.o and contributors
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容