Junior — Middle
How can a suspended function (suspend) be executed in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a suspended function (suspend function) is called from a coroutine or another suspended function. You cannot call a suspend function directly from regular code.
Example of calling a suspend function:
import kotlinx.coroutines.*
suspend fun fetchData(): String {
delay(1000) // simulate a long operation
return "Data received"
}
fun main() = runBlocking {
val result = fetchData() // calling suspend function inside a coroutine
println(result)
}
Here, runBlocking starts a coroutine within which suspend functions can be called. In Android, lifecycleScope.launch or other CoroutineScope are usually used to call suspend functions.