Search code examples
kotlinkotlin-coroutinescoroutinesuspend

Are Kotlin suspend functions blocking?


Code:

suspend fun main() {
    println("main start")
    f1()
    println("main end")
}

suspend fun f1() {
    println("f1 start")
    delay(2_000)
    println("f1 end")
}

Actual Output:

main start
f1 start
f1 end
main end

My expected output

main start
f1 start
main end
f1 end

Does this mean suspend functions are blocking unlike JS?


Solution

  • That is the default behavior read more about suspending functions here, if you want to run f1 asynchronously you have to use async as:

    suspend fun main() {
        withContext(Dispatchers.Main) {
            println("main start")//Run in main
            val getF1 = async(Dispatchers.IO) { f1() } // Run f1 in IO
            println("main end") // Run in main
            println(getF1.await())//Run in main
        }
    }
    
    suspend fun f1() : String {
        println("f1 start")
        delay(2_000)
        println("f1 end")
        return "f1 result"
    }