Junior — Middle
What is the purpose and application of the suspend keyword in programming languages?
sobes.tech AI
Answer from AI
The keyword suspend in Kotlin (often used in Android development) denotes a function that can be paused and resumed later without blocking the thread.
This is the basis of coroutines — a mechanism for asynchronous and non-blocking programming. Functions with suspend can only be called from other suspend functions or coroutines.
Example:
suspend fun fetchData(): String {
delay(1000) // pauses the coroutine for 1 second
return "Data loaded"
}
Here, delay is also a suspend function that does not block the thread but simply pauses the execution of the coroutine.