Phi*_*yev 20 gradle kotlin kotlin-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"
}
}
Run Code Online (Sandbox Code Playgroud)
和 main.kt
fun main(args: Array<String>) {
launch (CommonPool) {
delay(1000L)
println("World!")
}
println("Hello, ")
Thread.sleep(2000L)
}
Run Code Online (Sandbox Code Playgroud)
当我跑步时,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`
Run Code Online (Sandbox Code Playgroud)
Tas*_*iwa 19
如果您使用的是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"
Run Code Online (Sandbox Code Playgroud)
Chr*_*ian 14
启动不再直接使用。在科特林文档建议使用:
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
}
}
Run Code Online (Sandbox Code Playgroud)
就像评论中已经回答的那样,kotlinx.coroutines.experimental.*包缺少导入。如果您愿意,可以在GitHub 上查看我的示例。
import kotlinx.coroutines.experimental.*
fun main(args: Array<String>) {
launch(CommonPool) {
delay(1000)
LOG.debug("Hello from coroutine")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7916 次 |
| 最近记录: |