Are you wondering if there’s a better way to incorporate asynchronous operations in your Android app rather than using AsyncTask? Well, there is! And in this tutorial, we’ll explore how replacing AsyncTask with Kotlin’s Coroutines can enhance your app’s performance.
Replace AsyncTask with Kotlin’s Coroutines
Adding Coroutine Support
First, we need to add Coroutine support to our Android Studio project. Simply add the following dependencies to the module-level build.gradle file:
dependencies {
…
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0’
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0’
}
Once the dependencies have been added, sync the project to make Kotlin Coroutines available for use.
Using Coroutines
Implement a CoroutineScope
The CoroutineScope instance is required for using coroutines. Therefore, implementing a CoroutineScope in your wrapper class makes it accessible. Here’s an implementation example in an activity class:
class SomeActivity : AppCompatActivity(), CoroutineScope by MainScope() {
…
override fun onDestroy() {
super.onDestroy()
cancel()
}
}
MainScope handles the CoroutineScope implementation logic and allows using CoroutineScope’s methods. Canceling on onDestroy() ensures no asynchronous logic continues to run after activity completion.
AsyncTask Replacement with Coroutines
The async() method is a simple to use AsyncTask replacement. It runs asynchronously on the same thread as started and updates views without the burden of using the correct thread, as required by AsyncTask. Here’s an example of replacing AsyncTask with Coroutines:
private fun doOperation() {
async {
delay(10_000)
val someTextView = findViewById(R.id.some_text_view)
someTextView.text = “SomeString”
}
}
async() returns a Deferred instance, which can be paused and waited for using the await() method. We defer the result of async() when calculating something expensive that does not affect UI rendering or to wait for computation to complete.
Return Values with async
Kotlin Coroutines’ async() allows returning a value too. Here’s an example:
private fun doOperation() {
val result = async {
delay(10_000)
“SomeResult”
}
val someTextView = findViewById(R.id.some_text_view)
someTextView.text = result.await()
}
We access the Deferred instance’s result using the await() method and update the UI.
FAQs
1. Why should you replace AsyncTask in your app?
AsyncTask has been deprecated by Google and can also lead to app crashes, primarily when used inefficiently. Replacing it with Kotlin coroutines is a more modern and recommended approach that improves your app’s performance.
2. Which version of Kotlin Coroutines should you use?
You should use the latest version of Kotlin Coroutines. As of now, the latest version is 1.5.0.