Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin coroutines. Difference between launch{ fun} and launch {suspend fun}

Is there any difference in execution between?

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

And

launch {
   function2()
}
suspend fun function2(){
   DoSomething...
}
like image 231
Kunta Kinte Avatar asked Mar 06 '18 15:03

Kunta Kinte


People also ask

What is suspended fun in Kotlin?

A suspending function is simply a function that can be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking. The syntax of a suspending function is similar to that of a regular function except for the addition of the suspend keyword.

What is the difference between launch and async in Kotlin coroutines?

Kotlin launch vs async coroutines The launch launches a new coroutine concurrently with the rest of the code, which continues to work independently. The async creates a coroutine and can return the result of the asynchronous task. Start a coroutine that returns some result.

What is the difference between suspending vs blocking Kotlin?

BLOCKING: Function A has to be completed before Function B continues. The thread is locked for Function A to complete its execution. SUSPENDING: Function A, while has started, could be suspended, and let Function B execute, then only resume later. The thread is not locked by Function A.

What is coroutines launch?

Launching a Coroutine as a Job The launch {} function returns a Job object, on which we can block until all the instructions within the coroutine are complete, or else they throw an exception. The actual execution of a coroutine can also be postponed until we need it with a start argument. If we use CoroutineStart.


Video Answer


1 Answers

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?

like image 97
hotkey Avatar answered Oct 14 '22 07:10

hotkey