Sample in "delay" not work


#1

I run sample code in “https://kotlinlang.org/docs/reference/coroutines/basics.html” , but not work . And error tip shows "Suspend function ‘delay’ should be called only from a coroutine or another suspend function“ in IDEA.


#2

They all seem to work for me (running them from the website). Which sample do you have problems with?


#3

first sample code in “https://kotlinlang.org/docs/reference/coroutines/basics.html

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
}

#4

which version of ‘kotlinx-coroutines-core’ you use ?


#5

I found sample code can works when i update kotlinx.coroutines to 0.30.2 version and use experimental api . But kotlinx.coroutines to 1.0.0 still not work , and IDEA shows error message of “Suspend function ‘delay’ should be called only from a coroutine or another suspend function” . So i guess sample code is base on kotlinx.coroutines 0.30.2 version .


#6

It works on 1.0.0 version for me.


#7

Same for me. Make sure that you are on version 1.0.0 or higher for coroutines and Kotlin version 1.3


#8

It final works after updating kotlin plugin version to “1.3.0” in IDEA . Thank you for your advice ~