Suspend Functions
The suspend function in Kotlin is a suspendable function that can run inside a coroutine. It can pause execution to let other operations run and then resume when done, making it easy to write asynchronous I/O and concurrent code concisely.
Syntax
// Defining a suspend function
suspend fun functionName(param: Type): ReturnType {
// Can only be called from within a coroutine
delay(1000) // Wait 1 second (does not block the thread)
return result
}
// Calling a suspend function (from within a coroutine scope)
runBlocking {
val result = functionName(param)
}
Syntax Reference
| Keyword / Function | Description |
|---|---|
| suspend fun | Defines a suspendable function. Can only be called from within a coroutine. |
| runBlocking { } | Launches a coroutine and blocks the current thread until it completes. Used in tests and the main function. |
| coroutineScope { } | Suspends until all child coroutines complete (does not block the thread). |
| delay(ms) | Suspends the coroutine for the specified number of milliseconds (does not block the thread). |
| withContext(Dispatcher) { } | Switches the coroutine's context (thread) and executes the block. |
Sample Code
import kotlinx.coroutines.*
// Define suspend functions
suspend fun fetchData(id: Int): String {
delay(500) // Simulate a network request (wait 0.5 seconds)
return "Data-$id"
}
suspend fun processData(data: String): String {
delay(200) // Simulate processing time
return data.uppercase()
}
fun main() = runBlocking {
println("Start")
// Call suspend functions sequentially
val data = fetchData(1)
println("Fetched: $data") // Fetched: Data-1
val result = processData(data)
println("Processed: $result") // Processed: DATA-1
// Group child coroutines with coroutineScope
coroutineScope {
val a = fetchData(2)
val b = fetchData(3)
println("$a, $b") // Data-2, Data-3
}
println("Done")
}
Notes
A suspend function can only be called from within a coroutine or another suspend function. To call one from a regular function, you need to create a coroutine scope using runBlocking or launch.
Use delay() instead of Thread.sleep(), as it suspends the coroutine without blocking the thread. By launching multiple suspend functions concurrently inside a coroutine, you can achieve high throughput with fewer threads.
For launching coroutines concurrently, see launch / async. For retrieving asynchronous results, see await() / Deferred.
If you find any errors or copyright issues, please contact us.