Last Updated | 15 September 2020 |
The tutorial assumes you have prior knowledge of the coroutines and Kotlin Flow concepts.
Debugging works for
kotlinx-coroutines-core
version 1.3.8 or later.
Create a Kotlin flow with a slow emitter and a slow collector:
Open a Kotlin project in IntelliJ IDEA. If you don't have a project, create one.
Open the main.kt
file in src/main/kotlin
.
The src
directory contains Kotlin source files and resources. The main.kt
file contains sample code that will print Hello World!
.
Create the simple()
function that returns a flow of three numbers:
Change the code in the main()
function:
runBlocking()
block to wrap a coroutine.collect()
function.delay()
function to imitate CPU-consuming code. It suspends the coroutine for 300 ms without blocking the thread.println()
function.Build the code by clicking Build Project.
Set a breakpoint at the at the line where the emit()
function is called:
Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
The Debug tool window appears:
Resume the debugger session by clicking Resume program in the Debug tool window. The program stops at the same breakpoint.
Now the flow emits the second value.
Open the main.kt
file in src/main/kotlin
.
Enhance the code to run the emitter and collector concurrently:
buffer()
function to run the emitter and collector concurrently. buffer()
stores emitted values and runs the flow collector in a separate coroutine.Build the code by clicking Build Project.
Set a new breakpoint at println(value)
.
Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
The Debug tool window appears.
In the Coroutines tab, you can see that there are two coroutines running concurrently. The flow collector and emitter run in separate coroutines because of the buffer()
function. The buffer()
function buffers emitted values from the flow. The emitter coroutine has the RUNNING status, and the collector coroutine has the SUSPENDED status.
Resume the debugger session by clicking Resume program in the Debug tool window.
Now the collector coroutine has the RUNNING status, while the emitter coroutine has the SUSPENDED status. You can dig deeper into each coroutine to debug your code.
© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/tutorials/coroutines/debug-flow-with-idea.html