Trying to run some examples for Kotlin coroutines, but can't build my project. I'm using the latest gradle release - 4.1
Any suggestions what to check/fix?
Here is build.gradle
buildscript { ext.kotlin_version = '1.1.4-3' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'kotlin' apply plugin: 'application' kotlin { repositories { jcenter() } experimental { coroutines 'enable' } dependencies { compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18" } }
and the main.kt
fun main(args: Array<String>) { launch (CommonPool) { delay(1000L) println("World!") } println("Hello, ") Thread.sleep(2000L) }
when I run gradle compileKotlin
I get the following
e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (2, 5): Unresolved reference: launch e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (2, 13): Unresolved reference: CommonPool e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (3, 9): Unresolved reference: delay`
Quoting definition of Global Scope from Kotlin's documentation– “Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.” GlobalScope creates global coroutines and these coroutines are not children of some specific scope.
The simplest way to create a coroutine is by calling the launch builder on a specified scope. It Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is canceled when the resulting job is canceled. The launch doesn't return any result.
Launch isn't used anymore directly. The Kotlin documentation suggests using:
fun main() { GlobalScope.launch { // launch a new coroutine in background and continue delay(1000L) println("World!") } println("Hello,") // main thread continues here immediately runBlocking { // but this expression blocks the main thread delay(2000L) // ... while we delay for 2 seconds to keep JVM alive } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With