kotlin GlobalScope, runBlocking is not available in kotlin.coroutines.*
Asked Answered
S

1

9

I have multi module kotlin gradle project in github here.

One of my sub project introducing-coroutines with build file build.gradle.kts file is here

The contents of build.gradle.kts is -

    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
        }
    }

I'm trying to create my first coroutine program from this 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
}

The issue is GlobalScope is not available in kotlin.coroutines.* or kotlinx.coroutines.*. Below is the screenshot -

gradle version - 5.1.1 kotlin version - 1.3.11 kotlinx-coroutines-core - 1.1.0

GlobalScope compile time error

Can anyone help me the package import details what is package GlobalScope/ runBlocking required?

Syphon answered 19/1, 2019 at 2:6 Comment(0)
S
12

The simplest way to solve your issue is to replace

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

with

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

So why do you need to remove kotlin function? If you check its source code (below) you will see that it appends module name to string "org.jetbrains.kotlin:kotlin-" so in your case the final string becomes "org.jetbrains.kotlin:kotlin-org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0" which is obviously invalid and should cause an error (but it doesn't, so it is a bug).

/**
 * 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" } ?: ""}"
Slack answered 19/1, 2019 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.