Bird
Raised Fist0
Kotlinprogramming~10 mins

Suspend functions concept in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Suspend functions concept
Call suspend function
↓
Suspend execution
↓
Other work runs
↓
Resume suspend function
↓
Complete function and return
Shows how a suspend function pauses its work, lets other code run, then resumes later.
Execution Sample
Kotlin
import kotlinx.coroutines.*

suspend fun fetchData(): String {
    delay(1000)
    return "Data"
}

fun main() = runBlocking {
    val result = fetchData()
    println(result)
}
This code calls a suspend function that waits 1 second, then returns a string.
Execution Table
StepActionStateOutput
1Call fetchData()Start fetchData, delay begins
2delay(1000) suspends fetchDatafetchData paused, main continues
3runBlocking waits for fetchDataWaiting for fetchData to resume
4After 1 second, fetchData resumesfetchData resumes after delay
5fetchData returns "Data"fetchData completes
6main receives resultresult = "Data"
7println(result)Prints to consoleData
8Program endsAll done
💡 fetchData completes and returns, main prints result, program ends
Variable Tracker
VariableStartAfter Step 4After Step 6Final
resultundefinedundefined"Data""Data"
Key Moments - 3 Insights
Why does fetchData pause at delay(1000) instead of blocking?
Because delay is a suspend function that pauses fetchData without blocking the thread, letting other code run (see Step 2 in execution_table).
How does main wait for fetchData to finish?
main uses runBlocking which waits for fetchData to complete before continuing (see Step 3 and Step 6).
What happens after fetchData resumes from suspension?
It continues running from where it paused, returns the result, and main receives it (see Steps 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does fetchData pause execution?
AStep 4
BStep 2
CStep 6
DStep 7
💡 Hint
Check the 'Action' and 'State' columns in Step 2 where delay suspends fetchData.
According to variable_tracker, what is the value of 'result' after Step 6?
A"Data"
Bnull
Cundefined
Dempty string
💡 Hint
Look at the 'After Step 6' column for 'result' in variable_tracker.
If delay was replaced with a blocking Thread.sleep, how would the execution_table change?
Amain would continue without waiting
BfetchData would suspend as before
CfetchData would not pause; main would block immediately
DProgram would crash
💡 Hint
Consider how blocking calls differ from suspend functions in Kotlin coroutines.
Concept Snapshot
suspend fun name() { ... } defines a suspend function.
Inside, suspend functions like delay() pause without blocking.
Caller must be in coroutine or runBlocking to call suspend functions.
Execution suspends and resumes later, enabling non-blocking waits.
Useful for asynchronous tasks like network or delay.
Full Transcript
This visual trace shows how Kotlin suspend functions work. When fetchData is called, it starts and hits delay(1000), which suspends fetchData without blocking the thread. The main function waits using runBlocking. After 1 second, fetchData resumes, returns "Data", and main prints it. Variables like result change from undefined to "Data" after fetchData completes. Key points: suspend functions pause and resume, delay suspends without blocking, and runBlocking waits for suspend functions to finish.

Practice

(1/5)
1. What is the main purpose of a suspend function in Kotlin?
easy
A. To mark the function as deprecated
B. To make the function run faster by using multiple threads
C. To allow the function to pause and resume without blocking the thread
D. To convert the function into a lambda expression

Solution

  1. Step 1: Understand what suspend functions do

    Suspend functions let the program pause execution at some point and resume later without blocking the thread.
  2. Step 2: Compare options with this behavior

    Only To allow the function to pause and resume without blocking the thread describes this pausing and resuming behavior correctly.
  3. Final Answer:

    To allow the function to pause and resume without blocking the thread -> Option C
  4. Quick Check:

    Suspend function purpose = pause and resume without blocking [OK]
Hint: Suspend means pause and resume without blocking [OK]
Common Mistakes:
  • Thinking suspend means multithreading
  • Confusing suspend with deprecated functions
  • Assuming suspend converts functions to lambdas
2. Which of the following is the correct way to declare a suspend function in Kotlin?
easy
A. fun suspend fetchData() { }
B. fun fetchData() suspend { }
C. suspend fetchData fun() { }
D. suspend fun fetchData() { }

Solution

  1. Step 1: Recall suspend function syntax

    The correct syntax places the suspend keyword before fun.
  2. Step 2: Check each option

    Only suspend fun fetchData() { } matches the correct syntax: suspend fun fetchData() { }.
  3. Final Answer:

    suspend fun fetchData() { } -> Option D
  4. Quick Check:

    Suspend function syntax = suspend before fun [OK]
Hint: Remember: suspend keyword comes before fun [OK]
Common Mistakes:
  • Placing suspend after fun
  • Putting suspend after function name
  • Mixing order of keywords
3. What will be the output of the following Kotlin code?
import kotlinx.coroutines.*
suspend fun greet() {
    delay(100)
    println("Hello from suspend")
}
fun main() = runBlocking {
    greet()
    println("Done")
}
medium
A. Hello from suspend\nDone
B. Done\nHello from suspend
C. Compilation error because greet() is suspend
D. Runtime error because delay() is not allowed here

Solution

  1. Step 1: Understand runBlocking and suspend call

    runBlocking starts a coroutine and allows calling suspend functions like greet().
  2. Step 2: Trace execution order

    greet() delays 100ms, then prints "Hello from suspend". After greet() finishes, main prints "Done".
  3. Final Answer:

    Hello from suspend\nDone -> Option A
  4. Quick Check:

    Output order = greet() then Done [OK]
Hint: runBlocking lets you call suspend functions directly [OK]
Common Mistakes:
  • Assuming greet() runs asynchronously and prints after Done
  • Thinking delay causes errors outside coroutine
  • Confusing suspend function calls outside coroutines
4. Identify the error in this Kotlin code snippet:
fun fetchData() {
    delay(1000)
    println("Data fetched")
}
medium
A. delay() cannot be called from a non-suspend function
B. println() is not allowed inside functions
C. fetchData() must return a value
D. delay() requires an integer argument, 1000 is invalid

Solution

  1. Step 1: Check usage of delay()

    delay() is a suspend function and can only be called from suspend functions or coroutines.
  2. Step 2: Analyze fetchData() declaration

    fetchData() is a regular function without suspend keyword, so calling delay() inside causes an error.
  3. Final Answer:

    delay() cannot be called from a non-suspend function -> Option A
  4. Quick Check:

    delay() call requires suspend function context [OK]
Hint: delay() only works inside suspend functions [OK]
Common Mistakes:
  • Thinking delay() works in normal functions
  • Believing println() is restricted
  • Confusing delay() argument type
5. You want to write a suspend function fetchUserData() that calls another suspend function fetchFromNetwork() and returns its result. Which of the following is the correct way to implement fetchUserData()?
hard
A. fun fetchUserData() = fetchFromNetwork()
B. suspend fun fetchUserData() = fetchFromNetwork()
C. fun suspend fetchUserData() = fetchFromNetwork()
D. suspend fun fetchUserData() { fetchFromNetwork() }

Solution

  1. Step 1: Recognize suspend function chaining rules

    A suspend function calling another suspend function must itself be marked suspend.
  2. Step 2: Check each option's syntax and behavior

    suspend fun fetchUserData() = fetchFromNetwork() correctly declares fetchUserData() as suspend and returns fetchFromNetwork() result. The option with suspend fun fetchUserData() { fetchFromNetwork() } misses returning the result. The remaining options have incorrect syntax.
  3. Final Answer:

    suspend fun fetchUserData() = fetchFromNetwork() -> Option B
  4. Quick Check:

    Calling suspend inside suspend requires suspend keyword [OK]
Hint: Suspend functions calling suspend must also be suspend [OK]
Common Mistakes:
  • Omitting suspend keyword on calling function
  • Using wrong suspend syntax order
  • Not returning the result from called suspend function
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard