What is Suspend Function in Kotlin: Simple Explanation and Example
suspend function in Kotlin is a special function that can pause its execution without blocking the thread, allowing other work to run. It is used with Kotlin coroutines to write asynchronous, non-blocking code in a simple and readable way.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of just standing there doing nothing, you start chopping vegetables while waiting. A suspend function works similarly: it can pause its work (like waiting for water) and let other tasks run (like chopping vegetables) without blocking the whole kitchen.
In Kotlin, marking a function with suspend means it can pause at certain points and resume later. This pause and resume happen without blocking the main thread, so your app stays responsive. The function uses Kotlin's coroutine system to manage this smoothly behind the scenes.
Example
This example shows a suspend function that waits for 1 second before printing a message. The main function runs the coroutine and waits for it to finish.
import kotlinx.coroutines.* suspend fun waitAndPrint() { delay(1000L) // Pause for 1 second without blocking println("Hello after 1 second") } fun main() = runBlocking { println("Start") waitAndPrint() // Call suspend function println("End") }
When to Use
Use suspend functions when you need to perform tasks that take time, like downloading data, reading files, or waiting for user input, without freezing your app. They help keep your app smooth and responsive by not blocking the main thread.
For example, in Android apps, network calls should be done inside suspend functions to avoid freezing the user interface. Similarly, any long-running operation can benefit from being a suspend function.
Key Points
- suspend functions can pause and resume without blocking threads.
- They must be called from a coroutine or another suspend function.
- They make asynchronous code easier to write and read.
- Used mainly for long-running or delayed tasks.