0
0
Kotlinprogramming~5 mins

Suspend functions concept in Kotlin

Choose your learning style9 modes available
Introduction

Suspend functions let your program pause and wait without blocking everything else. This helps your app stay smooth and fast.

When you want to fetch data from the internet without freezing the screen.
When you need to read or write files but don't want the app to stop working.
When you want to wait for a timer or delay without blocking other tasks.
When you want to run long tasks but keep the app responsive.
When you want to handle multiple tasks at the same time easily.
Syntax
Kotlin
suspend fun functionName(parameters): ReturnType {
    // code that can pause
}
Use the suspend keyword before fun to mark a function as suspend.
Suspend functions can only be called from other suspend functions or coroutine builders.
Examples
A simple suspend function that returns a string after some work.
Kotlin
suspend fun fetchData(): String {
    // pretend to get data
    return "Data received"
}
This suspend function waits for 1 second without blocking, then prints a message.
Kotlin
suspend fun waitAndPrint() {
    kotlinx.coroutines.delay(1000) // pause for 1 second
    println("Done waiting")
}
Sample Program

This program shows how to call a suspend function greet inside runBlocking. It pauses inside greet without freezing the whole program.

Kotlin
import kotlinx.coroutines.*

suspend fun greet() {
    delay(500) // pause for half a second
    println("Hello from suspend function!")
}

fun main() = runBlocking {
    println("Start")
    greet() // call suspend function
    println("End")
}
OutputSuccess
Important Notes

Suspend functions do not create new threads by themselves; they just let the current task pause.

You need a coroutine builder like runBlocking or launch to call suspend functions from normal code.

Summary

Suspend functions let your code pause and resume without blocking.

Use suspend keyword before fun to create them.

Call suspend functions only from coroutines or other suspend functions.