【问题标题】:kotlin GlobalScope, runBlocking is not available in kotlin.coroutines.*kotlin GlobalScope,runBlocking 在 kotlin.coroutines 中不可用。*
【发布时间】:2019-01-19 02:06:07
【问题描述】:

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

我的一个子项目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 科特林版本 - 1.3.11 kotlinx-coroutines-core - 1.1.0

谁能帮我包导入详细信息包GlobalScope/runBlocking需要什么?

【问题讨论】:

    标签: kotlin coroutine kotlinx.coroutines kotlin-extension


    【解决方案1】:

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

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

    compile("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" } ?: ""}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 2021-03-28
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多