未解决的参考:启动

时间:2017-09-10 00:00:29

标签: gradle kotlin kotlinx.coroutines

尝试为Kotlin协同程序运行一些示例,但无法构建我的项目。我使用最新的gradle版本 - 4.1

有什么建议要检查/修复?

以下是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"
    }
}

main.kt

fun main(args: Array<String>) {
    launch (CommonPool) {
        delay(1000L)
        println("World!")
    }

    println("Hello, ")
    Thread.sleep(2000L)
}

当我运行gradle compileKotlin时,我得到以下内容

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`

4 个答案:

答案 0 :(得分:6)

如果您使用的是Coroutines 1.0+,则不再导入

  

导入kotlinx.coroutines.experimental。*

但是

  

导入kotlinx.coroutines.launch

您需要在build.gradle的依赖项关闭中(对于协程1.0.1)执行以下操作:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1"

答案 1 :(得分:3)

不再直接使用启动。 Kotlin documentation建议使用:

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
    } 
}

答案 2 :(得分:2)

与评论中已经回答的一样,kotlinx.coroutines.experimental.*包中缺少导入。如果您愿意,可以在GitHub查看我的示例。

import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) {

    launch(CommonPool) {
        delay(1000)
        LOG.debug("Hello from coroutine")
    }

}

答案 3 :(得分:0)

尝试这种方式

///将此行添加到gradle

 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.kotlinx_coroutines"
 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.kotlinx_coroutines"


  class xyz{
     private val job = Job()
        private val coroutinesScope: CoroutineScope = CoroutineScope(job + Dispatchers.IO)

      ....
     . ...
       coroutinesScope.launch {
                       // task to do
                        Timber.d("Delete Firebase Instance ID")
                    }


    // clear the job
      job.cancel()

    }