2

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?

Harsh
  • 350
  • 1
  • 4
  • 13
Abhay P
  • 107
  • 7
  • What gave you the impression that you would get the second output? Kotlin suspend functions are part of Kotlin’s coroutine support - the unique selling point is that it makes asynchronous code _seem to_ act like synchronous code. – Boris the Spider Oct 04 '20 at 08:04
  • I dont understand how this is non blocking. Isnt this blocking? Execution waits for 2s in `f1()` before printing `main end`. My understanding of non blocking is that execution does not wait for anything. As soon as execution sees `delay` it moves to the next available instruction which is `println("main end")` – Abhay P Oct 04 '20 at 08:11
  • Execution waits. The thread doesn’t. That’s the whole point of structured concurrency. It is best modelled and understood as callbacks. – Boris the Spider Oct 04 '20 at 08:28

1 Answers1

3

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"
}
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • Thanks. This makes it clear. I misunderstood because I assumed that each suspend function creates its own coroutine. But in fact in my code only one coroutine is created. – Abhay P Oct 04 '20 at 21:37