未解析引用:1.3中Kotlin中的异步
我在github有多模块kotlin gradle项目 我的一个子项目介绍了与build文件build.gradle.kts文件的协同程序,它是 build.gradle.kts的内容是-未解析引用:1.3中Kotlin中的异步,kotlin,coroutine,kotlinx.coroutines,kotlin-extension,Kotlin,Coroutine,Kotlinx.coroutines,Kotlin Extension,我在github有多模块kotlin gradle项目 我的一个子项目介绍了与build文件build.gradle.kts文件的协同程序,它是 build.gradle.kts的内容是- import org.jetbrains.kotlin.gradle.dsl.Coroutines import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { java kotlin
import org.jetbrains.kotlin.gradle.dsl.Coroutines
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
java
kotlin("jvm") version "1.3.11"
}
group = "chapter2"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
compile(kotlin("stdlib-jdk8"))
compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0")
testCompile("junit", "junit", "4.12")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
我可以导入import kotlinx.coroutines.async
,没有任何问题,但不确定为什么会出现此错误
我已经验证了类似的问题,并添加了ankocommons
dependency
如何解决此错误?问题在于(与launch
相同)被定义为CoroutineScope
上的扩展函数。在下面的示例中,它在与上下文的接收方CoroutineScope
中调用:
suspend fun computecr(array: IntArray, low: Int, high: Int): Long {
return if (high - low <= SEQUENTIAL_THRESHOLD) {
(low until high)
.map { array[it].toLong() }
.sum()
} else {
withContext(Default) {
val mid = low + (high - low) / 2
val left = async { computecr(array, low, mid) }
val right = computecr(array, mid, high)
left.await() + right
}
}
}
suspend-fun-computecr(数组:IntArray,低:Int,高:Int):长{
返回如果(高-低首先您必须从Gradle中删除启用实验性协同程序功能的部分
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
您不能再隐式地使用async()
函数。您必须为全局作用域协程GlobalScope.async(){…}
显式调用它,或者您可以使用CoroutineScope(…).async{…}
或从作用域函数CoroutineScope{…}
,with context(…)从另一个协程作用域调用它{…}
我写了一篇供个人使用的文章,以了解协同程序是如何工作的。我希望它是好的和有用的。您可以尝试以下内容:
CoroutineScope(Dispatchers.Default).async {
...
}
这里提到“在GlobalScope实例上使用async或launch是非常不鼓励的。”@Bunthai Deng我同意这一点。我知道,我只是写了所有可能的方法来启动一个协同程序!我没有提到好的或坏的做法!
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
CoroutineScope(Dispatchers.Default).async {
...
}