Android AsyncTask vs Thread + Handler vs rxjava
Since no one's replying. I'm answering my own questions then.
- The reason why
AsyncTask
is recommended for only short tasks (around 5 seconds) is there is no method to cancel a runningAsyncTask
. There exists a method calledAsyncTask.cancel(true)
which invokesonCancelled(Result result)
. However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand,Thread
can be stopped withThread.interrupt()
. - There shouldn't be any problem running an
AsyncTask
within aService
provided that you are aware of the cancellation limitation ofAsyncTask
and the possibility of memory leak can be created byAsyncTask
. Note that, there is obviously no need to use anAsyncTask
in anIntentService
which is already running in a worker thread. - This is a very experience-based question. I guess there would be no complete answer. What we can do is to understand Rx and being aware of the its limitations to determine where suitable to use it. In my development work, I use
RxJava
all the time without having any issue. Note that the same memory leaking issue is also applied toRxJava
. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation withRxJava
that can be easily found by Googling.
AsyncTask and Thread+Handler are not carefully designed and implemented. RxJava, Akka and other frameworks for asynchronous execution seem more carefully developed.
Each technology has its limitations. AsyncTask is for a single parallel task with ability to show progress on UI. However, if activity is regenerated (e.g. because of screen rotating), connection to UI is lost (one possible solution for this problem is at https://github.com/rfqu/AsyncConnector).
Thread+Handler
keeps memory for thread stack even when there is no messages to process. This limits the possible number of threads. You can have much more Akka actors
or RxJava Subscribers
than handler threads, with similar functionality.