How to replace AsyncTask with Kotlin 2021 Coroutines tips

0


This tutorial explains how to replace AsyncTask with Kotlin coroutines. We will do our best to make sure you understand this guide. I hope you will like this blog How to replace AsyncTask with Kotlin coroutines. If your answer is yes, please share after reading this.

Check out how you can replace AsyncTask with Kotlin coroutines

For a long time on Android, if you had to do something asynchronously while building an app, you would probably use AsyncTask. AsyncTask is an API in the Android framework that makes it easy (ish) to perform background operations and return values ​​when completed. And that makes sense. Unlike Kotlin’s coroutines, AsyncTask has been around for a while and is built-in.

However, the design philosophy and implementation of AsyncTask has become somewhat outdated over the years. For this reason, Google deprecated the AsyncTask API. You can still use it if you want, but Google doesn’t recommend it. Fortunately, there are many alternatives to AsyncTask, including a feature of the Kotlin language: coroutines.

The Kotlin Coroutine API is an incredibly powerful framework that lets you do a ton of things. This article will only scratch the surface of what is possible. We’ll go over the basics needed to migrate from AsyncTask to coroutines.

Added support for coroutine

Before you can start using coroutines, you must add them to your project.

Added support for Kotlin

If you have 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 Coroutine Libraries

In your module-level build.gradle, include the following dependencies.

Dependencies {

implementation ‘org.jetbrains.kotlinx: kotlinx-coroutines-core: 1.5.0’

implementation ‘org.jetbrains.kotlinx: kotlinx-coroutines-android: 1.5.0’

}

Synchronize your project and Kotlin coroutines are now available.

Use coroutines

Implement a CoroutineScope

To use coroutines, you must have a CoroutineScope instance. An easy way to do this is to just implement it in your wrapper class.

For example, to implement a CoroutineScope in an activity:

SomeActivity class: AppCompatActivity, CoroutineScope by MainScope () {

replace fun onDestroy () {

super.onDestroy ()

To cancel()

}

}

This will cause SomeActivity to implement the CoroutineScope interface through the MainScope class. MainScope will handle all of the CoroutineScope implementation logic, while allowing you to use CoroutineScope methods. Calling cancel () on onDestroy () ensures that no asynchronous logic continues to execute after the activity is completed.

Replacing AsyncTask with Coroutines

Suppose you have an AsyncTask in an Activity that performs a long-running background operation and ultimately returns a string. Something similar to the following.

private inner class SomeTask: AsyncTask () {

replace fun doInBackground (vararg parameters: Void): String {

to treat {

// Imagine this is a real operation that takes 10 seconds and not just idle.

Thread.sleep (10,000);

} catch (e: Exception thrown) {}

returns “A string”;

}

replace fun onPostExecute (result: String) {

val someTextView = findViewById (R.id.some_text_view)

someTextView.text = result

}

}

Replacing it with a coroutine is easy. Just use the async () method. Kotlin’s async () runs on the thread it was started on, but it does so asynchronously. This means that you can update views and so on without having to worry about using the correct thread.

SomeActivity class: AppCompatActivity (), CoroutineScope by MainScope () {

private fun Operation () {

async {

// Inside coroutine scopes (like inside async here), delay is used instead of Thread.sleep.

delay (10,000)

val someTextView = findViewById (R.id.some_text_view)

someTextView.text = “A string”

}

}

}

As you can see, using coroutines can be much easier than using AsyncTask. However, you don’t need to call async () and let it do its job. You can keep a referral and even wait for it to complete.

val asyncJob = async {

// An operation

}

// Pause here until the end of the asynchronous block.

asyncJob.await ()

// This will not run until the asyncJob is finished, but other operations started before the job or from another method can still be performed.

do something else ()

Return values ​​with async

You can even return a value from async () if you want. So the original example could become something like this.

SomeActivity class: AppCompatActivity (), CoroutineScope by MainScope () {

private fun Operation () {

val asyncJob = async {

// Inside coroutine scopes (like inside async here), delay is used instead of Thread.sleep.

delay (10,000)

// Regardless of the type of the last line, this is what async () ultimately returns.

“Some string”

}

val result = asyncJob.await ()

val someTextView = findViewById (R.id.some_text_view)

someTextView.text = result

}

}

Using withContext

For convenience, Kotlin provides withContext (). This inserts the entire wait () element and just returns the value to you.

SomeActivity class: AppCompatActivity (), CoroutineScope by MainScope () {

private fun Operation () {

// Asynchronous execution on the main thread.

val result = withContext (Dispatchers.Main) {

delay (10,000)

“A certain result”

}

val someTextView = findViewById (R.id.some_text_view)

someTextView.text = result

}

}

Final words: how to replace AsyncTask with Kotlin coroutines

hope you will understand this item How to replace AsyncTask with Kotlin coroutines, if your answer is no, you can request anything through the contact forum section linked to this article. And if your answer is yes, then share this article with your family and friends.


Share.

Leave A Reply