Sobes.tech
Junior — Middle

How can a suspended function be launched in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, a suspended function (suspend function) does not run directly; it can only be called from another suspended function or from a coroutine. To run a suspended function, you need to create a coroutine using constructs like launch or async from the kotlinx.coroutines library.

Example of running a suspended function:

import kotlinx.coroutines.*

suspend fun doWork() {
    delay(1000)
    println("Work completed")
}

fun main() = runBlocking {
    launch {
        doWork()  // launching a suspended function inside a coroutine
    }
}

Here, runBlocking creates a coroutine in the main thread, and launch starts a new coroutine in which the suspended function doWork is called. Thus, the suspended function is executed inside a coroutine.