协程,没有 Android,缺少带有主调度程序的模块

Dam*_*les 11 kotlin kotlin-coroutines

我正在尝试在 IntellJ 的 Kotlin 控制台项目中测试 Coroutine。我添加了这个库:org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.0。它有效,直到我使用Dispatchers.Main. 添加后,抛出运行时异常。

import kotlinx.coroutines.*
val scope = CoroutineScope(Dispatchers.Main);
fun main(args: Array<String>) {
    scope.launch {  }
}
Run Code Online (Sandbox Code Playgroud)

java.lang.IllegalStateException:缺少带有主调度程序的模块。添加提供主调度程序的依赖项,例如“kotlinx-coroutines-android”,并确保它与“kotlinx-coroutines-core”具有相同的版本

我按照现有答案的建议切换了库org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0,但随后它引发了不同的运行时错误。

NoClassDefFoundError:android/os/Looper

看起来这个库是针对 Android 的。使用“kotlinx-coroutines-android”是 Kotlin 控制台项目的正确解决方案吗?如果没有,我该如何解决这个问题?

Jof*_*rey 2

Dispatchers.Main很可能不是您想要的。它的目的是在 GUI 应用程序的主事件循环上调度协程。

\n

对于控制台应用程序,尤其是您在此处共享的代码片段,您可能希望使用主线程(在其中main()执行)作为事件循环,并防止main()在协程完成之前返回。这是通过 using 来完成的runBlocking,它会阻止外部代码的当前线程,但将其用作传递CoroutineScopethislambda 的事件循环runBlocking

\n

所以你的代码可能应该是这样的:

\n
import kotlinx.coroutines.*\n\nfun main() {\n    runBlocking { // this: CoroutineScope\n\n        // there is a CoroutineScope here, the receiver is implicit\n        launch {\n            // this code will run in the main thread,\n            // concurrently with other coroutines and other code\n            // in the runBlocking lambda\n        }\n        // this code will run in the main thread,\n        // concurrently with the launch and other coroutines\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

如果您确实有 GUI 应用程序,则可以检查Dispatchers.Main 的 KDoc以查看根据您的目标平台使用哪个调度程序。如果您以 JVM 为目标,则需要额外的依赖项来引入与您使用的 UI 技术相对应的调度程序。KDoc 中也对此进行了描述:

\n
\n

为了在 JVM 上使用主调度程序,应将以下工件添加到项目运行时依赖项中:

\n
    \n
  • kotlinx-coroutines-android\xe2\x80\x94 用于 Android 主线程调度程序

    \n
  • \n
  • kotlinx-coroutines-javafx\xe2\x80\x94 用于 JavaFx 应用程序线程调度程序

    \n
  • \n
  • kotlinx-coroutines-swing\xe2\x80\x94 用于 Swing EDT 调度程序

    \n
  • \n
\n
\n