Junior — Middle
How to call a suspend function from a standard function within coroutines?
sobes.tech AI
Answer from AI
To call a suspend function from a regular (non-suspend) function, you need to launch a coroutine, as suspend functions can only be executed within a coroutine context. You can use runBlocking (if you need blocking execution) or create a coroutine using CoroutineScope.launch or CoroutineScope.async.
Example with runBlocking:
fun standardFunction() {
runBlocking {
suspendFunction()
}
}
suspend fun suspendFunction() {
println("Executing suspend function")
}
If you do not want to block the thread, it is better to use CoroutineScope.launch:
fun standardFunction() {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
suspendFunction()
}
}
Thus, calling a suspend function from a regular function is only possible within a coroutine.