Reputation: 1562
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?
Upvotes: 0
Views: 2041
Reputation: 4698
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.
Upvotes: 2
Reputation: 164
AsyncTask is abstract class and it must be subclassed. AsyncTask has 4 steps: onPreExecute, doInBackground, onProgressUpdate and onPostExecute. They are executed serially on single background thread.
If you want to fetch a URL or perform a heavyweight computation in Android, you have to use async programming.
they can be used when there is small task to communicate with main thread. for tasks that use multiple instances in parallel.
Thread is a concurrent unit of execution. It has its own call stack. With threads, the operating system switches running threads preemptively according to its scheduler.
they can be used for tasks running in parallel use Multiple threads.
for task where you want to control the CPU usage relative to the GUI thread.
Coroutines use to write asynchronous code that will look like normal sequential code. they can provide a very high level of concurrency with very little overhead.
Upvotes: 4