Is there any difference in execution between?
launch {
function1()
}
fun function1(){
DoSomething...
}
And
launch {
function2()
}
suspend fun function2(){
DoSomething...
}
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With