Howto use coroutines in M1.3


#1

What is the right way to use coroutines under M1.3 (EAP)?
I am obviously missing some basic ingredience, because coroutine “hello-world”

fun main(args: Array<String>) {
     launch {
        delay(1000)
        println("Hello")
    }
}

will not compile. launch and delay cannot be resolved.

The following are my kotlin related parts from build.gradle.kts

plugins {
    kotlin("jvm") version "1.3.0-rc-116"
}

apply {
    plugin("kotlin")
}

kotlin {
    experimental {
        coroutines = Coroutines.ENABLE
    }
}

dependencies {
    compile(kotlin("stdlib-jdk8"))
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

I guess, the experimental part is no longer needed in 1.3.


#2

You need to import launch and delay I believe. They are not keywords in the language, but rather functions defined in some package.


#3

Unfortunately, they are not available as imports (launch will only autocomplete to javafx.application.Application.launch).
Other functions from the corouting package like suspendCoroutine are available, that is why I believe something is missing in the configuration (jvm specific intrinsics?).


#4

You need to add a dependency on kotlinx.coroutines library, where these functions are declared.

The latest version of that library for Kotlin 1.3 is 0.27.0-eap13.

Note that the top-level launch and async functions are deprecated, you can find how to use them properly here: https://medium.com/@elizarov/structured-concurrency-722d765aa952


#5

Thank you. It works now.


#6

Reading that article I’m now finally getting a grasp on how to use coroutines in Kotlin 1.3.

The documentation doesn’t seem to do a very good job to me of explaining how to use coroutines other than giving runBlocking() which is not what I wanted, and didn’t do a very good job at all (in my opinion) of explaining how to use GlobalScope or how to use the new version of launch() with a CoroutineScope.

It doesn’t help of course that almost all articles, posts and code examples that one finds are using coroutines from Kotlin 1.1 or 1.2.

I think a few more introductory articles in the manual on how to implement CoroutineScope, how to supply a CoroutineContext, what dispatchers to choose from etc wouldn’t be amiss.