kotlin coroutines. Difference between launch{ fun} and launch {suspend fun}
Asked Answered
E

2

8

Is there any difference in execution between?

launch {
    function1()
}
fun function1(){
    DoSomething...
}

And

launch {
   function2()
}
suspend fun function2(){
   DoSomething...
}
Essive answered 6/3, 2018 at 15:46 Comment(0)
S
9

Yes, there is.

Semantically, a call to a suspending function may suspend the execution, which may be resumed at some point later (or never), possibly in a different context (e.g. another thread).

To ensure this, the compiler handles calls to a suspending function in a special way: it produces the code that saves the current local variables into a Continuation instance and passes it to the suspending function, and there's also a resumption point in the bytecode after the call, to which the execution will jump, load the local variables and run on (with a corner case of tail calls).

A call to a non-suspending function is compiled to much simpler bytecode, the same to normally calling a function outside a suspending function body.

You can find details about Kotlin coroutines design and implementation here: Coroutines for Kotlin

You can also inspect the resulting compiled bytecode to see the difference: Kotlin Bytecode - How to analyze in IntelliJ IDEA?

Sher answered 6/3, 2018 at 17:41 Comment(0)
D
0

Let me add in a few cents

You are basically asking for the difference between a function and a suspended function.

A coroutine is like a thread only that it doesn't take so much of computer memory. You can start 100,000 coroutines with ease. A suspend function is basically just a function but with a special call scope. It can only be called from coroutines and other suspended functions. From the official Kotlin documentation, it says

Suspend functions are only allowed to be called from a coroutine or another suspend function. Let's dig a little into what it means. The biggest merit of coroutines is that they can suspend without blocking a thread. The compiler has to emit some special code to make this possible, so we have to mark functions that may suspend explicitly in the code.

Directed answered 7/3, 2018 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.