Should I Still Use Kotlin AsyncTask in 2021? Pros and Cons
AsyncTask is an Android API that handles asynchronous jobs. To put this another way, AsyncTask provides a mechanism for handling background jobs.
Some processes in an app might be too heavy or involve waiting for responses. It’s not recommended to execute such processes on the main UI thread as it can cause the UI thread to pause until a response is returned. And that’s where AsyncTask comes in with its doInBackground() method.
In this post, I’ll answer if you should still use AsyncTask in 2021. In addition, I’ll discuss how the AsyncTask API works. We’ll also take a look at the pros and cons of AsyncTask and some alternatives.
Let’s start by explaining how the AsyncTask API works.
Kotlin AsyncTask API
AsyncTask is an Android-specific API that makes working on the UI easier. Three generic types define an AsyncTask. The three generics are listed below:
- Params: The Params generic type specifies the AsyncTask’s inputs.
- Progress: This is a type that returns the data on the level of progress on the execution.
- Result: The final generic returns the output from the background task. For example, in an AsyncTask that handles requests to fetch JSON data from a remote endpoint, Result may return a JSON formatted string.
You may set any of the generics to Void. And that would mean no value will be provided or returned.
The 4 Execution Steps of AsyncTask
AsyncTask gets heavy or delayed jobs off the UI thread and updates Result or Progress back to the UI. There are four steps for doing this. The steps are as follows:
- onPreExecute(): This method is executed before the method that handles the actual background task. Also, it runs on the UI thread. It handles operations that should occur just before the start of execution—for example, the code to display a progress bar.
- doInBackground(): This is where the execution of the actual background task occurs. Hence, it’s invoked on the background thread. In addition, this step publishes progress updates to the UI thread. Finally, the results from the heavy or delayed task must be returned in this step.
- onProgressUpdate(): As the name suggests, this is where the updates published by doInBackground() are accessible. This stage is invoked on the UI thread. Hence, it’s possible to update views here using the progress status.
- onPostExecute(): Now, this is where you close that progress bar. It’s the final step and where the result from doInBackground() is returned. This step is also invoked on the UI thread. Hence, you can perform actions like updating views here.
Example of Kotlin AsyncTask
The following is a code sample for Kotlin AsyncTask. The code implements the doInBackground() and onPostExecute() methods.
The above code simply returns the string “Yeah!” as a result from the background task. However, in a real application, the result may be the response from a network request. Then, the result is printed out to the Logcat in the post execute step.
Pros and Cons of AsyncTask
Now that we have a good understanding of AsyncTask, let’s see some pros and cons.
AsyncTask is now a member of the infamous deprecated club. Hence, we should forget using it in 2021. However, below are some pros of AsyncTask that might make anyone still consider using it.
- Doesn’t require a third-party library: AsyncTask is part of the Android API. As a result, it does not require an extra library or plugins. That’s to say, you can start using AsyncTask in your Kotlin project without downloading any external dependencies.
- Supports Kotlin and Java: You can use AsyncTask in both Kotlin and Java projects.
- Prevents blocking of UI thread: AsyncTask provides methods for doing heavy jobs off the UI or main thread. Hence, it prevents such tasks from blocking the UI. The doInBackground() method prevents blocking of the UI thread.
AsyncTask is deprecated in Android API 30. In other words, official support for the API has ended. Therefore, the Android team does not recommend AsyncTask. This on its own is a disadvantage. In this section, we’ll look at some of the reasons why you wouldn’t want to use AsyncTask.
- Memory leak: A memory leak occurs when an app is unable to deallocate the memory it assigned to an object. This is more likely to occur when handling background tasks. Therefore, it’s common with AsyncTask.
- Crashes on configuration changes: Configuration changes—for example, rotating the screen or changing the device orientation from portrait to landscape—can cause the Android platform to recreate the entire UI of an app. However, AsyncTask has a close association with the UI. Hence, a configuration change may cause AsyncTask to crash an app.
- Complex to understand: Yes, AsyncTask can be hard to understand at first. Many developers found getting a grasp of what each of the three generics represents hard. In addition to that, it requires developers to remember which thread each of the AsyncTask steps runs on.
- Deprecated: Finally, as has been mentioned, as a result of all the issues with AsyncTask, it has been deprecated. Therefore, there will be no future updates or support to the AsyncTask API.
Should I Use AsyncTask in 2021?
Comparing the pros and cons, I’d say no. You should not use AsyncTask in 2021. This is because the disadvantages are greater than any advantage of doing so. In addition, best practice recommends the removal of any deprecated code from your application. As a result, you should not add new AsyncTask code to your project. Also, you should consider updating old code that still uses AsyncTask.
In the next section, we’ll take a look at some alternatives for AsyncTask.
Alternatives for AsyncTask in 2021
Today, we have many ways for handling asynchronous tasks in Android.
If you would prefer to use a solution that doesn’t require a third-party library, the official documentation for AsyncTask recommends Executors from java.util.concurrent.
Another alternative is Kotlin coroutines. This is an API for handling asynchronous tasks in Kotlin. Unlike AsyncTask, coroutine is life cycle aware. Therefore, there are fewer chances for memory leaks. This option is popular amongst Kotlin developers. Hence, it’s easy to learn as there are many resources out there.
Coroutines are highly testable. And there is an entire library dedicated to testing coroutines. The Kotlin coroutines test library makes writing unit tests for coroutines easy. Unit tests verify the behavior of a unit of your code—usually, a single function or method.
Lastly, Waldo offers a no-code testing solution for mobile engineers. With Waldo, it’s possible to test the results from an asynchronous task without any extra setup or code. You can try Waldo for free here.
To conclude, we’ll summarize everything we’ve been able to cover in this post.
We started by learning about what AsyncTask is. And we defined AsyncTask as an API for doing heavy tasks off the UI thread. Next, we looked at some pros and cons of AsyncTask.
Finally, we answered our main question of “Should I still use AsyncTask in 2021?” From all the facts available, the answer to the question is a simple no. Hence, don’t use AsyncTask for new projects. Consider using one of the alternatives we mentioned instead. The alternatives prevent memory leaks and have official support. For example, coroutines are recommended for doing asynchronous tasks in Kotlin.