Junior — Middle
How can you call a suspend function inside synchronous code?
sobes.tech AI
Answer from AI
You cannot call a suspend function directly from synchronous code because it requires a coroutine context. However, you can launch a coroutine and wait for the result in a blocking manner using the runBlocking function.
Example:
import kotlinx.coroutines.*
fun main() {
val result = runBlocking {
suspendFunction()
}
println(result)
}
suspend fun suspendFunction(): String {
delay(1000)
return "Result"
}
runBlocking creates a coroutine scope and blocks the current thread until the coroutine completes, allowing suspend functions to be used in synchronous code.