Some great alternatives for AsyncTasks

Shubham Soni
Code Yoga
Published in
6 min readMar 30, 2018

AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Thread pools assume that they will get their threads back after a reasonable period of time. Hence, AsyncTask is a poor choice when you do not know how long you need the thread (e.g., thread listening on a socket for a chat client, where you need the thread until the user exits the client).

If you create an AsyncTask that uses an activity context or the AsyncTask is and child of the activity/fragment, you keep the activity/fragment in memory. When you rotate or change activity in the period the AsyncTask is running. you keep your old activity instance in memory and are leaking the activity/fragment or If you are using an AsyncTask as a child of an Activity/Fragment or it uses the context of the Activity then it will keep the activity/fragment running in the memory even after the new ones are created.Like if you rotate the activity the AsyncTask will keep running making your old Activity instance Alive in the memory causing memory leaks…Here You have two options.

  • @SuppressLint(“StaticFieldLeak”) — Ignore the LINTs warning
  • Make you Inner nested Class static or use Top level Class instead if Using anonymous, local, and inner class.

If you are using an AsyncTask then you have to deal with this…either this or that way…

So lets look at some of great alternatives for replacing AsyncTasks and making our life much easier..

• AsyncTaskLoader :

AsyncTaskLoader performs the same function as the AsyncTask, but a bit better. It can handle Activity configuration changes more easily, and it behaves within the life cycles of Fragments and Activities. The nice thing is that the AsyncTaskLoader can be used in any situation that the AsyncTask is being used. Anytime data needs to be loaded into memory for the Activity/Fragment to handle, The AsyncTaskLoader can do the job better.

When compare AsyncTaskLoader vs. AsyncTask, as you may know when you rotate your device screen, it may destroy and re-create your activity, to make it clear let image rotate your device while networking transaction is going on:

AsyncTask will be re-executed as background thread again, and previous background thread processing was just be redundant and zombie.

AsyncTaskLoader will be just re-used basing on Loader ID that registered in Loader Manager before, so avoid re-executing network transaction.

• Volley :

Volley is a library that makes networking for Android apps easier and most importantly, faster.Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.

Advantages of Volley are:

  • Volley provides transparent disk and memory caching.
  • Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
  • Volley provides powerful customization abilities.
  • Volley provides Debugging and tracing tools

• Retrofit :

It’s released by Square, This offers very easy to use REST API’s.

  • Compared to Volley, Retrofit’s REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.
  • We can use it with any serialization library, with error handling.

• RxJava :

Its an better approach to RxJava instead of AsyncTask wherever possible.RxJava is “a library for composing asynchronous and event-based programs by using observable sequences”.While they can’t be compared directly but allows you to write less code to do the same.

Let’s say you have a login form. A naive implementation would be a direct chain of method calls, starting with your UI, like:

  1. user clicks the button
  2. initiate login request
  3. return the results of login request
  4. update UI

What happens when a config change occurs between #2 & #3? Your chain of method calls is broken, because your activity is gone. A better approach:

  1. Observe results/exceptions of login calls from UI
  2. User clicks login button
  3. UI serializes a future attempt to login
  4. Data/Network layer observes this serialization, executes a new network request, completely independent of your UI layer
  5. Because UI is already observing login call results (#1), your UI will be updated

So instead of a single LoginResult loginWith(Credentials credentials) method, I have two:

  • Observable<LoginResult> logins() (I'll begin observing this in onStart())
  • void loginWith(Credentials credentials)

This allows you to observe the results of the call separately from initiating it.

Services :

Services are a “Swiss Army knife” for a wide range of functions that do not require direct access to an activity’s user interface.

AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Thread pools assume that they will get their threads back after a reasonable period of time. Hence, AsyncTask is a poor choice when you do not know how long you need the thread (e.g., thread listening on a socket for a chat client, where you need the thread until the user exits the client).

AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.

Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.

• AsyncTaskScheduler :

Another alternative for AsyncTask.
1. execute tasks in parallel as default, rather than processing them sequentially

2. execute single task use a thread rather than an executor

3. you can set a default executor to execute tasks

4. a callback for task error

5. manage multiple tasks easily

6. you can you it on any thread ,anf it will have a callback on main thread。

LoopJ :

An asynchronous, callback-based Http client for Android built on top of Apache’s HttpClient libraries.

  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • HTTP requests happen outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • GET/POST params builder (RequestParams)
  • Multipart file uploads with no additional third party libraries
  • Tiny size overhead to your application, only 60kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Optional built-in response parsing into JSON (JsonHttpResponseHandler)
  • Optional persistent cookie store, saves cookies into your app’s SharedPreferences

• Thinr :

Thinr is a replacement for AsyncTask. It is a tiny library that makes things like the following possible in a leak free and configuration change aware way.

  • easy usage
  • easy to understand
  • no boilerplate code involved (when using Java 8)
  • easy to integrate
  • no need to rewrite your whole code base to make use of it / can be introduced step-by-step where it is needed while leaving all the other code untouched
  • non invasive (i.e. don’t forces you to use a special style of programming)
  • beautiful code (when using Java 8)

• Futuroid :

Futuroid is an Android library that allows running asynchronous tasks and attaching callbacks thanks to a convenient syntax. It offers an alternative to the Android AsyncTask class.

  • Future-based API (similar to Guava’s ListenableFutures, Scala/Akka Futures, Javascript promises…)
  • Allows registering callbacks to be run on the Android UI/main thread
  • Provides a default ExecutorService (fixed thread pool with 5 threads) that can be replaced by a custom one
  • Each task can be run on the default ExecutorService or on a custom one
  • Allows task chaining (monad-style)

• BoltsFrameworks :

Bolts is a collection of low-level libraries designed to make developing mobile apps easier. Bolts was designed by Parse and Facebook for our own internal use, and we have decided to open source these libraries to make them available to others.Bolts Tasks have many advantages over other methods of asynchronous programming, such as callbacks and AsyncTask.

  • They consume fewer system resources, since they don’t occupy a thread while waiting on other Tasks.
  • Performing several Tasks in a row will not create nested "pyramid" code as you would get when using only callbacks.
  • Tasks are fully composable, allowing you to perform branching, parallelism, and complex error handling, without the spaghetti code of having many named callbacks.
  • You can arrange task-based code in the order that it executes, rather than having to split your logic across scattered callback functions

• Needle :

Its an Multithreading library and a good alternative for asynctasks.

• Nanotasks :

NanoTasks is an extremely light way to execute code in the background on Android. It is a wrapper around AsyncTask that provides a simpler to use and more flexible API.

• TeaSpoon :

It makes more clear and easy to execute your method on ui thread or background thread.

  • Eliminate runOnUiThread calls by using @OnUi on method.
  • Make background logic more clear by using @OnBackground on method.

• SugarTask :

Another simple and good alternative for AsyncTask.SugarTask is so simple that it just works good for easy task and simple Tasks.

--

--

Shubham Soni
Code Yoga

Senior Executive @Ketto @Dart @Flutter @Java @Android, Editor @FlutterCommunity @CodeBurst.io, App Developer @Senior @Moderator @FlutterDeveloper