Reputation: 255
I am getting unresolved references working with coroutines in Kotlin. I don't know how to update build.gradle file on vs code. Do I have to import some extensions or paths? Here's the code below
import kotlin.coroutines.*
fun main() {
val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending")
repeat(3) {
GlobalScope.launch {
println("${Thread.currentThread()} has started")
for(i in states) {
println("${Thread.currentThread()} - $i")
delay(5000)
}
}
}
}
The Output gives unresolved reference regarding GlobalScope.launch() and delay()
Upvotes: 1
Views: 3485
Reputation: 37829
GlobalScope
, launch
and delay
are not part of the Kotlin standard library, they are part of the Kotlinx coroutines library.
To use them, you need to add the coroutines library to your build.gradle(.kts):
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0")
}
And then import these declarations:
import kotlinx.coroutines.*
As a side note, you shouldn't use GlobalScope
unless you know what you're doing, and I guess you're just learning coroutines right now so you may want to avoid using this. In general, you should use a coroutine scope that is tied to some component with a lifecycle instead.
In this case, you probably want to use runBlocking { ... }
around the body of your main method, which will block the main thread while you're waiting for your coroutines.
Upvotes: 6