Debug coroutines using IntelliJ IDEA
最近更新 | 2020-09-17 |
The tutorial assumes you have prior knowledge of the coroutines concept.
Debugging works for
kotlinx-coroutines-core
version 1.3.8 or later.
Create coroutines
-
Open a Kotlin project in IntelliJ IDEA. If you don't have a project, create one.
-
Open the
main.kt
file insrc/main/kotlin
.The
src
directory contains Kotlin source files and resources. Themain.kt
file contains sample code that will printHello World!
. -
Change code in the
main()
function:- Use the
runBlocking()
block to wrap a coroutine. - Use the
async()
function to create coroutines that compute deferred valuesa
andb
. - Use the
await()
function to await the computation result. - Use the
println()
function to print computing status and the result of multiplication to the output.
import kotlinx.coroutines.* fun main() = runBlocking<Unit> { val a = async { println("I'm computing part of the answer") 6 } val b = async { println("I'm computing another part of the answer") 7 } println("The answer is ${a.await() * b.await()}") }
- Use the
-
Build the code by clicking Build Project.
Debug coroutines
-
Set breakpoints at the lines with the
println()
function call: -
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:
- The Frames tab contains the call stack.
- The Variables tab contains variables in the current context.
- The Coroutines tab contains information on running or suspended coroutines. It shows that there are three coroutines. The first one has the RUNNING status, and the other two have the CREATED status.
-
Resume the debugger session by clicking Resume program in the Debug tool window:
Now the Coroutines tab shows the following:
- The first coroutine has the SUSPENDED status – it is waiting for the values so it can multiply them.
- The second coroutine is calculating the
a
value – it has the RUNNING status. - The third coroutine has the CREATED status and isn’t calculating the value of
b
.
-
Resume the debugger session by clicking Resume program in the Debug tool window:
Now the Coroutines tab shows the following:
- The first coroutine has the SUSPENDED status – it is waiting for the values so it can multiply them.
- The second coroutine has computed its value and disappeared.
- The third coroutine is calculating the value of
b
– it has the RUNNING status.
Using IntelliJ IDEA debugger, you can dig deeper into each coroutine to debug your code.