Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference: launch

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` 
like image 238
Philipp Grigoryev Avatar asked Sep 10 '17 00:09

Philipp Grigoryev


People also ask

What is GlobalScope in Kotlin?

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.

How do I launch coroutine Kotlin?

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.


1 Answers

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     }  } 
like image 74
Christian Avatar answered Sep 28 '22 19:09

Christian