Suspend Functions in Kotlin
Hi 👋 feel free to reach out to me at ‘‘ my Medium’’. I’m always open to new ideas, collaborations, and conversations. Stay connected!

Suspend Functions in Kotlin

A suspend function in Kotlin is a special type of function that can be paused and resumed without blocking the thread. It is designed to work inside coroutines, which provide a scope for executing asynchronous, non-blocking code. Coroutines leverage suspend functions to handle long-running tasks efficiently, making the code look synchronous while running asynchronously under the hood.

What is a Suspend Function?

  • A suspend function is a special type of function that can pause execution without blocking the main thread and can resume later.
  • Defined using the suspend keyword.

suspend fun fetchData(): String {
    delay(2000) // Simulates a network call
    return "Data fetched!"
}        


Key Features of Suspend Functions

  • Non-Blocking: They don’t block the thread while waiting.
  • Can Only Be Called from a Coroutine: Suspend functions must be called from either another suspend function or a coroutine scope.
  • Pauses and Resumes: They pause at suspension points (e.g., delay) and resume once the task is complete.


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


Common Suspend Functions in Kotlin Coroutines

  • delay(timeMillis: Long) - Pauses for a specified time without blocking.
  • withContext(context) - Switches execution to a different thread or dispatcher.
  • await() - Waits for the result of an asynchronous operation.


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:

  1. Suspend functions do not run on a separate thread by default. They run within the same thread unless specified with a dispatcher like Dispatchers.IO.
  2. Dispatcher Switching allows offloading heavy tasks to background threads:

withContext(Dispatchers.IO) {
    // Perform IO tasks like database or network calls
}        


  1. runBlocking {} blocks the main thread, whereas launch and async allow non-blocking operations.
  2. Suspend functions alone don’t create coroutines. They must be called inside a coroutine scope.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics