How to replace AsyncTask with Kotlin’s Coroutines – Guide

For a long time on Android, if you needed to do something asynchronously when creating an app, you’d probably be using AsyncTask. AsyncTask is an API in the Android framework that makes it easy (ish) to perform operations in the background and return values ​​when done. And that makes sense. Unlike Kotlin’s coroutines, AsyncTask has been around for some time and is integrated. However, both the design philosophy and implementation of AsyncTask have become somewhat outdated over the years. Because of this, Google suspended the use of the AsyncTask API. You can still use it if you like, but Google doesn’t recommend doing so. Fortunately, there are a bunch of alternatives to AsyncTask, including an feature of the Kotlin language – coroutines. Kotlin’s Corroutine API is an incredibly powerful framework that lets you do a lot of things. This article will only scratch the surface of what is possible. We will go over the fundamentals needed to migrate from AsyncTask to coroutines.

Adding Cortina Support

Before you start using coroutines, you really need to add them to your project.

Adding Kotlin Support

If you’ve already implemented Kotlin, skip to the next section. Otherwise, you will need to add Kotlin support to your project. see my tutorial on how to add Kotlin to an existing project for more details.

Adding Corroutine Libraries

In your module-level build.gradle, add the following dependencies. dependencies { … implementation ‘org.jetbrains.kotlinx: kotlinx-coroutines-core: 1.5.0’ implementation ‘org.jetbrains.kotlinx: kotlinx-coroutines-android: 1.5.0’ } Sync your project and Kotlin’s routines will be available for use.

Using Cortinas

Implementing a CoroutineScope

To use coroutines, you will need to have a CoroutineScope instance available. An easy way to do this is to just implement it in the containing class. For example, to implement a CoroutineScope in an activity: class SomeActivity: AppCompatActivity, CoroutineScope by MainScope() { … override fun onDestroy() { super.onDestroy() cancel() } } This will make SomeActivity implement the CoroutineScope interface through the MainScope class. MainScope will handle all the CoroutineScope implementation logic, while allowing you to use the CoroutineScope methods. Calling cancel() on onDestroy() ensures that no asynchronous logic continues to run after the activity exits.

Replacing AsyncTask with Corroutines

Let’s say you have an AsyncTask inside an Activity that performs a long-running operation in the background and eventually returns a String. Something like the following. SomeTask private inner class: AsyncTask () { override fun doInBackground (vararg params: Void): String { Try it { // Pretend this is a real operation that takes 10 seconds and doesn’t just sleep. Thread.sleep (10000); } catch (e: InterruptedException) {} return “SomeString”; } override fun onPostExecute (result: String) { val someTextView = findViewById (R.id.some_text_view) someTextView.text = result } } Replacing this with a coroutine is easy. Just use the async() method. Kotlin’s Async() runs on whatever Thread it was started on, but asynchronously. This means you can update Views and others without having to worry about using the right Topic. class SomeActivity: AppCompatActivity(), CoroutineScope from MainScope() { … private fun doOperation() { asynchronous { // Within coroutine scopes (like within asynchronous here), delay is used instead of Thread.sleep. delay (10,000) val someTextView = findViewById (R.id.some_text_view) someTextView.text = “SomeString” } } } As you can see, using coroutines can be much simpler than using AsyncTask. However, you don’t need to just call async() and let it do its work. You can keep a reference to it and even wait for it to finish. val asyncJob = async { // Some operation } // Pause here until the asynchronous block completes. asyncJob.await() // This won’t run until asyncJob ends, but other operations started before the job, or started from another method, can still run. doSomethingElse()

Returning values ​​with asynchronous

You can even return an async() value if you wish. So the original example can become something like this. class SomeActivity: AppCompatActivity(), CoroutineScope from MainScope() { … private fun doOperation() { val asyncJob = async { // Within coroutine scopes (like within asynchronous here), delay is used instead of Thread.sleep. delay (10,000) // Whatever the type of the last line is what async() eventually returns. “SomeString” } val result = asyncJob.await() val someTextView = findViewById (R.id.some_text_view) someTextView.text = result } }

Using withContext

For convenience, Kotlin provides comContext(). This aligns all of the await() and returns the value to you. class SomeActivity: AppCompatActivity(), CoroutineScope from MainScope() { … private fun doOperation() { // Run asynchronously on Main Thread. val result = withContext (Dispatchers.Main) { delay (10,000) “SomeResult” } val someTextView = findViewById (R.id.some_text_view) someTextView.text = result } }

Final note

I hope you like the guide How to replace AsyncTask with Kotlin’s Coroutines. In case if you have any query regards this article you may ask us. Also, please share your love by sharing this article with your friends.

How to replace AsyncTask with Kotlin s Coroutines  2022  - 45How to replace AsyncTask with Kotlin s Coroutines  2022  - 70How to replace AsyncTask with Kotlin s Coroutines  2022  - 37How to replace AsyncTask with Kotlin s Coroutines  2022  - 93