Issue
I have read about Kotlin coroutines recently and now, I wonder what is the difference between asyncTask class and multi Thread programming and coroutines? in what situation I should use each one?
Solution
AsyncTask
was the first hand solution proposed by Google in Android SDK in order to process work in the background, while keeping the main thread free from many complex operations. In fact, AsyncTask
let you to do complex processing in an asynchronous manner. Compared to classical Java Thread
, the AsyncTask
was somehow specialized, providing UI wrappers around threads in order to allow a more enjoyable experience as a developer, coding in an async way. The AsyncTask
class was deprecated in the meantime and the recommended way to solve things is by using coroutines.
Coroutines are not a new concept introducer by Kotlin, in fact this concept exists in a lot of programming languages (Go has Goroutines and Java will provide something called Fibers). The main advantage of using coroutines is the simplicity of code, the only thing that differentiate a sync task/function in face of an async task/function is the usage of suspend
keyword put in front of the function.
For example, the following function is executed in a synchronous way:
fun doSomething() = println("Print something")
while the following one is executed on a asynchronous way, due to the usage of suspend
keyword:
suspend fun doSomething() = println("Print something")
When a suspend
function is reached, the program will not block there, and will go further in running the rest of the code, but will receive a Continuation
which will return the value computed by the suspended function when this one will be available.
Answered By - Dina Bogdan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.