I went through the Kotlin Coroutine, I understood how it works but I have a confusion between Kotlin coroutine & Android Async.execute() & Async await. The Kotlin coroutine runs in the background and does not block on the UI thread but the same thing happens when we start android AsyncTask(with the methods doInBackground
onPostExecute
and onProgressUpdate
overridden), it also does the computation in a background thread and publishes the result on the UI thread.
Async-await returns a Deffered object means the result will obviously going to be returned in future.
Can Anyone Explain what's the difference between these.
Let's try to break this down:
The Kotlin coroutine runs in the background
A coroutine CAN run in the background
does not block on the UI thread
Let's talk about what a coroutine is:
A coroutine can be thought of as the code that gets passed to one of the coroutine builder functions i.e. launch {}
By definition when a coroutine is launched, suspend functions within it do not block the corresponding Thread
when they are reached; they "pause" the coroutine.
When the suspension point is reached, it is as if you were telling the code to "call you back later" when the result is available; a suspension point can be though of as a callback.
Let's look at an example:
fun main() {
val job = MainScope().launch {
doSomeWork()
}
suspend fun doSomeWork() {/*expensive work goes here*/}
}
When doSomeWork()
is reached the code will suspend the coroutine, i.e. the suspend modifier is indicating to the coroutine framework that it can go do some other coroutine related work and then come back to this point when doSomeWork()
is done.
Since this coroutine is launched using MainScope()
it will be launched in the main Thread
. That is why I said that coroutines CAN run in a background Thread
but not always do so. In this case it does not, but it still does not block the UI Thread
.
In the other hand, AsyncTask
was (it is deprecated as of API 30) a mechanism that performed a tasks in a background Thread
and posted the result back to the UI Thread
For the difference between CoroutineScope.async{}
and CoroutineScope.launch{}
we can look at the return values for each. As I showed in the example. launch{}
returns a Job
which is a representation of the lifecycle of the coroutine itself. Using the Job
you can cancel()
or join()
the coroutine; you have control over its lifecycle. As you mention, async{}
returns a Deffered<T>
which is a representation of a future value. When await()
is called on the Deffered<T>
the coroutine is suspended until the result is ready to be consumed.
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