Search code examples
kotlincoroutinekotlinx.coroutines

Using kotlinx.coroutines in IntelliJ IDEA project


I am trying to learn coroutines and so I fire up IntelliJ and create a scratch file. But when I type in my coroutines I get compiler complaints such as runBlocking is an unresolved reference. So this is not an android project or any such thing. Just a scratch file in a basic Kotlin project.

How do I bring in the coroutine stuff so I stop getting errors?


Solution

  • runBlocking and other high-level coroutine utilities are not in the Kotlin standard library, but instead are a part of the library kotlinx.coroutines.

    To use this library in your project you must download its binaries and add a dependency on them to the project. Usually declaring a library dependency is a line or couple of lines in a build file, if you use build systems like Gradle or Maven. However in a plain IntelliJ project it's possible to get that library from Maven Central almost without hassle:

    • Open project structure
    • In the "Modules" page select a module which you use as a context of the scratch file (I suppose there will be just one module).
    • Switch to "Dependencies" tab and hit the plus button.
    • then in a context menu select "Library" -> "From Maven"
    • paste maven coordinates of the kotlinx.coroutines library artifact:

      org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3

      where 1.3.3 is the version of that library. You can find the latest available version here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/README.md

    • be sure to check "Transitive dependencies" and "Sources" boxes.

    After hitting OK the library will be downloaded from Maven Central repository with all its dependencies and added to your module. Then it will be possible to use runBlocking in your project or scratch files.