kotlin GlobalScope,runBlocking 在 kotlin.coroutines 中不可用。*

标签 kotlin coroutine kotlinx.coroutines kotlin-extension

我在 github 中有多模块 kotlin gradle 项目 here .

我的一个子项目introducing-coroutines与构建文件build.gradle.kts文件是here

build.gradle.kts 的内容是 -

    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(kotlin ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0"))
        testCompile("junit", "junit", "4.12")
    }

    configure<JavaPluginConvention> {
        sourceCompatibility = JavaVersion.VERSION_1_8
    }


    tasks.withType<KotlinCompile> {
        kotlinOptions.jvmTarget = "1.8"
    }

    kotlin {
        experimental {
            coroutines   = Coroutines.ENABLE
        }
    }

我正在尝试从此 link 创建我的第一个协程程序.

import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello,") // main thread continues while coroutine is delayed
    Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}

问题是 GlobalScopekotlin.coroutines.*kotlinx.coroutines.* 中不可用。下面是截图 -

gradle 版本 - 5.1.1 Kotlin 版本 - 1.3.11 kotlinx-coroutines-core - 1.1.0

GlobalScope compile time error

任何人都可以帮我了解包导入详细信息需要什么包 GlobalScope/runBlocking 吗?

最佳答案

解决问题的最简单方法是更换

compile(kotlin("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0"))

编译(“org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0”)

那么为什么需要删除 kotlin 函数呢?如果您检查其源代码(如下),您将看到它将模块名称附加到字符串 "org.jetbrains.kotlin:kotlin-" 因此,在您的情况下,最终字符串变为 "org. jetbrains.kotlin:kotlin-org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0" 这显然是无效的,应该会导致错误(但事实并非如此,所以这是一个错误)。

/**
 * Builds the dependency notation for the named Kotlin [module] at the given [version].
 *
 * @param module simple name of the Kotlin module, for example "reflect".
 * @param version optional desired version, unspecified if null.
 */
fun DependencyHandler.kotlin(module: String, version: String? = null): Any =
    "org.jetbrains.kotlin:kotlin-$module${version?.let { ":$version" } ?: ""}"

关于kotlin GlobalScope,runBlocking 在 kotlin.coroutines 中不可用。*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54263514/

相关文章:

android - 具有 Retrofit、Coroutines 和 Suspend 功能的并行请求

android - Kotlin Coroutines 等到完成 init block

android - Kotlin 启动协程跳过 Google Volley 从服务器检索信息的代码行

验证和 DDD - kotlin 数据类

android - Mapbox SymbolLayer 隐藏标记

android - kotlin中如何将Unit转换为String(添加同步代码后UPD不起作用)

android - LifecycleScope.launchWhenStarted 是否安全?如果不安全,在什么情况下?

android - 挂起函数会挂起协程吗?

python - Python 何时会/不会暂停协程的执行?

junit - 模拟挂起函数在 Mockito 中返回 null