Issue
I'm pretty new to Kotlin and I want to compose AsyncTask executions similarly like I would do in Scala to make them run sequentialy(to avoid race condition):
def f(): Future[Unit]
def g(): Future[Unit]
f.map(_ -> g)
or
for {
_ <- f
_ <- g
} yield ()
To do this I would want to extend somehow my helper:
fun doAsync(handler: () -> Unit): AsyncTask<Void, Void, Unit> =
object : AsyncTask<Void, Void, Unit>() {
override fun doInBackground(vararg params: Void?) {
try {
handler()
}
catch (t: Throwable) {
Log.e("AsyncTask", "fail", t)
}
}
}.execute()
I know there is something like onPostExecute
but I don't know how to change my helper to use it.
Solution
Async tasks, after Honey Comb are run sequentially. Quoting from documentation
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with Build.VERSION_CODES.DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with Build.VERSION_CODES.HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
And, async task is designed for small operations, if you have a long running one, better use other Api s.
Also, you can always specify an executor, by calling executeOnExecutor()
Answered By - Debanjan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.