In this article, we will see how to call a suspend function from the normal functions in Kotlin.

What are suspend functions?

Suspend functions executed within the coroutine contexts are used to write asynchronous programming in Kotlin. These functions allow developers to write non-blocking code. These functions can be paused and resumed later without blocking the execution thread.

Suspend keyword is used to mark the function as suspend function.

Example of calling a suspend function from a normal function

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

suspend fun suspendFunction() {
    delay(1000)
    println("Suspend function executed!")
}

fun normalFunction() {
    println("Normal function started")
    runBlocking {
        suspendFunction()
    }
    println("Normal function resumed")
}

fun main() {
    normalFunction()
}

In the above example, we defined a suspend function called suspendFunction() which blocks the execution of the program by 1000 milliseconds and prints a message after that.

The normalFunction() is a normal function which calls the suspend function wrapped inside a runBlocking. A coroutine context will be created after calling the suspend function.

When normalFunction() is called, it starts by printing a message, suspends execution to wait for the suspend function to complete, and then resumes execution to print another message.

Note that when calling a suspend function from a normal function, it’s best practice to wrap the suspend function call within a coroutine builder such as runBlocking or launch. Using runBlocking make the suspend function run in a separate thread context.

Important takeaway:

While it is not recommended to avoid blocking the main thread for long periods of time, there are times when calling a suspend function within a normal function can still provide benefits in terms of code organization, reusability, and codebase migration.

However, it is also important to consider the potential effects on the application’s user interface and overall responsiveness.

Categorized in:

Tagged in:

,