Suspend Functions in Kotlin
What is a Suspend Function?
suspend fun fetchData(): String {
delay(2000) // Simulates a network call
return "Data fetched!"
}
Key Features of Suspend Functions
Example with Coroutine Scope
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Fetching data...")
val data = fetchData()
println(data)
println("Task Completed!")
}
suspend fun fetchData(): String {
delay(2000) // Pauses for 2 seconds without blocking
return "Data fetched!"
}
Suspend vs Regular Functions
Feature Suspend Function Regular Function Blocking Behavior Non-blocking Blocking Thread Usage Uses lightweight threads Uses actual threads Pause & Resume Can pause and resume Cannot pause; executes sequentially Call Restrictions Called only within coroutines Can be called anywhere
Recommended by LinkedIn
Common Suspend Functions in Kotlin Coroutines
Launching Coroutines with Suspend Functions
Parallel Execution Example:
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Fetching data...\n")
// Parallel task
launch {
repeat(5) {
println("Task A running on ${Thread.currentThread().name}... $it")
delay(500) // Suspend, not block
}
}
launch {
repeat(5) {
println("Task B running on on ${Thread.currentThread().name}... $it")
delay(500) // Suspend, not block
}
}
val data = fetchData() // Suspends, but other tasks can continue
println(data)
repeat(5) {
println("Task Completed! --> $it")
}
}
suspend fun fetchData(): String {
println("suspend function enter")
delay(2001) // Suspend here
println("suspend function exit")
return "Data fetched!"
}
output:-)
Fetching data...
suspend function enter
Task A running on main... 0
Task B running on on main... 0
Task A running on main... 1
Task B running on on main... 1
Task A running on main... 2
Task B running on on main... 2
Task A running on main... 3
Task B running on on main... 3
suspend function exit
Data fetched!
Task Completed! --> 0
Task Completed! --> 1
Task Completed! --> 2
Task Completed! --> 3
Task Completed! --> 4
Task A running on main... 4
Task B running on on main... 4
Important Notes:
withContext(Dispatchers.IO) {
// Perform IO tasks like database or network calls
}