Junior — Middle
Explain what a suspend function is and how it works in Kotlin.
sobes.tech AI
Answer from AI
A suspend function in Kotlin is a function that can be paused and resumed later without blocking the thread. It is used for writing asynchronous, non-blocking code, for example, for network operations or long-running tasks.
Such functions are declared with the keyword suspend. Inside a suspend function, you can call other suspend functions, which allows writing sequential code that runs asynchronously under the hood.
Example:
suspend fun fetchData(): String {
delay(1000) // pauses execution for 1 second without blocking the thread
return "Data received"
}
Here, delay is a suspend function that pauses execution, allowing other coroutines to run during this time.
Thus, suspend functions help write asynchronous code more simply and cleanly, avoiding callback hell.