0
0
KotlinHow-ToBeginner · 3 min read

How to Create Suspend Function in Kotlin: Simple Guide

In Kotlin, you create a suspend function by adding the suspend keyword before the fun keyword. This marks the function as able to pause and resume execution, allowing asynchronous code to run without blocking threads.
📐

Syntax

A suspend function in Kotlin is declared by placing the suspend keyword before the fun keyword. This tells Kotlin that the function can be paused and resumed later, which is useful for asynchronous tasks.

  • suspend: Marks the function as suspendable.
  • fun: Declares a function.
  • functionName(): The name and parameters of the function.
  • Return type: Optional, like any function.
kotlin
suspend fun functionName(): ReturnType {
    // function body
}
💻

Example

This example shows a suspend function that simulates a delay, then returns a message. It demonstrates how to call a suspend function from a coroutine.

kotlin
import kotlinx.coroutines.*

suspend fun fetchMessage(): String {
    delay(1000L) // Simulates a long-running task
    return "Hello from suspend function!"
}

fun main() = runBlocking {
    println("Fetching message...")
    val message = fetchMessage() // Calling suspend function
    println(message)
}
Output
Fetching message... Hello from suspend function!
⚠️

Common Pitfalls

Common mistakes when creating or using suspend functions include:

  • Trying to call a suspend function from a regular function without a coroutine scope.
  • Forgetting to mark the function with suspend.
  • Blocking the thread inside a suspend function instead of using non-blocking calls like delay().

Always call suspend functions from a coroutine or another suspend function.

kotlin
/* Wrong: calling suspend function from regular function without coroutine */
fun wrongCall() {
    // val result = fetchMessage() // Error: suspend function called from non-suspend context
}

/* Right: calling suspend function inside coroutine or suspend function */
suspend fun rightCall() {
    val result = fetchMessage() // Correct
}

fun main() = runBlocking {
    rightCall()
}
📊

Quick Reference

Remember these key points when working with suspend functions:

  • suspend keyword marks a function as suspendable.
  • Suspend functions can only be called from coroutines or other suspend functions.
  • Use delay() for non-blocking pauses inside suspend functions.
  • runBlocking can start a coroutine in main for testing.

Key Takeaways

Use the suspend keyword before fun to create a suspend function.
Suspend functions can pause and resume without blocking threads, enabling asynchronous code.
Call suspend functions only from coroutines or other suspend functions.
Use delay() inside suspend functions for non-blocking waits.
Use runBlocking to run suspend functions in main or tests.