Programming question & answer

Suspend function 'delay' should be called only from a coroutine or another suspend function

RRTutors community answer Published Aug 16, 2021

Answer

In Kotlin when i want to run the coroutine code it retured compiler error like Suspend function 'delay' should be called only from a coroutine or another suspend function with below code

 

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking { 
    launch { doWorld() }
    println("Hello")

}


fun doWorld() {
    delay(1000L)
    println("World!")
}

 

 

To resolves error i have modifiled my code into like below, just added suspend keyword before the function doWorld()

 

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking { // this: CoroutineScope
    launch { doWorld() }
    println("Hello")

}

// this is your first suspending function
suspend fun doWorld() {
    delay(1000L)
    println("World!")
}

 

Now my code executed and return result. To resolves my error first we have to read about Coroutines and its scope.

Corouties will follow the strcutured  concurrency which means that Any new coroutine shuld be run inside a Coroutine scope or any other suspened function.

Read more about Coroutienscopes