How to replace AsyncTask with Kotlin’s Coroutines – Guide
Android has had an AsyncTask API for a while now, and it’s been integrated into the platform. This makes it easy to do operations in the background, and returns values when done. This is great for tasks that need to be completed quickly, or tasks that need to be completed multiple times.
Google has suspended the use of the AsyncTask API, citing outdated design philosophy and implementation. There are a number of alternatives available, including Kotlin’s coroutines feature. ..
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. 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 basics needed to migrate from AsyncTask to 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 basics needed to migrate from AsyncTask to coroutines. ..
Adding Cortina Support
coroutines are a powerful tool that can speed up your development process by allowing you to run code multiple times in succession. Before you start using coroutines, you really need to add them to your project.
Adding Kotlin Support
If you have already implemented Kotlin, please continue reading. Otherwise, you will need to add Kotlin support to your project. In this tutorial, we will learn how to add Kotlin support to an existing project.
Adding Corroutine Libraries
dependencies { compile ‘com.android.tools.build:gradle:3.0.0’ } In your project’s build.gradle, add the following dependencies. dependencies { compile ‘com.android.tools.build:gradle:3.0’ }
The implementation of Kotlinx-Coroutines-Core in JetBrains’ Kotlin development platform 1.5.0 is now available. This release includes a number of new features and improvements, including:
- Improved performance and memory usage when running coroutines on large data sets
- More reliable coroutine invocation and termination with improved error handling
- Improved support for multiple coroutines running in the same process
JetBrains has released a new version of KotlinX-Coroutines-Android, which provides improved performance. ..
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.
The CoroutineScope class provides a way to create and manage coroutines. A coroutine is a sequence of calls to a function, and can be used to speed up or delay execution of code. By using the CoroutineScope class, you can create custom coroutines that are specific to your application.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.coroutine = new CoroutineScope(); } }
super.onDestroy(); } This overrides the onDestroy() method of the super class, which will call when the object is destroyed.
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
AsyncTask myAsyncTask() { return new String( ); } This code will run in the background and return a String after a certain amount of time.
} AsyncTask is a private inner class that provides an asynchronous method.
} override fun doInBackground (vararg params: Void): String { if (!params) { return “”; // return without the parameter } // get the current context of the application. This can be retrieved using the Context object. var context = this.context ?? Context.current; // if there is no current context, get one from the system. if (!context) { // if there is no context, create one and return it. return “”; // return without the context
This is a simulated operation that takes 10 seconds and doesn’t just sleep.
If an interruption occurs while the code is running, an InterruptedException will be thrown. ..
if (result == “”) { println(“No result found”); } else { result = result.replace("\s+", “”) + “.”; } }
Some text view located at R.id.some_text_view. ..
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. Kotlin’s Async() method allows you to run code asynchronously, which means you can update Views and other components without worrying about using the right Topic. ..
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.coroutine = new CoroutineScope(); } @Override protected void onResume() { } @Override protected void onStop() {} }
} private fun doOperation() { }
Delaying a coroutine’s execution is a common way to improve performance.
SomeTextView.setText(new String(10))
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. ..
println(“Starting the async job”) } asyncJob.start()
The async block will pause the program until it completes.
AsyncJob will not run until the asyncJob completes, but other operations started before the job, or started from another method, can still run. ..
Returning values with asynchronous
You can even return an async() value if you wish. So the original example can become something like this. ..
This class SomeActivity is an AppCompatActivity and a CoroutineScope from MainScope. ..
} private fun doOperation() { }
val result = await job.run() println(result) } async { val result = await job.run() println(result) } ..
Delaying a coroutine’s execution is a common way to improve performance.
Async() eventually returns whatever the type of the last line is. ..
The await() method on the asyncJob object will return the result of the job as a Task object. ..
SomeTextView.setText(new String(10))
Using withContext
In Kotlin, comContext(). provides convenience for accessing the context of an object. This aligns all of the await() and returns the value to you.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.coroutine = new CoroutineScope(); } @Override protected void onResume() { } @Override protected void onStop() {} }
println(“Operation completed”) } fun main() { doOperation() // Operation completed } ..
Main Thread.RunAsynchronously();
val input = Dispatchers.Input val output = Dispatchers.Output output.write(“Hello, world!”) } With the context of the Main dispatcher, I wrote “Hello, world!” to the output. ..
SomeTextView.setText(new String(10))
Final note
This guide is about how to replace AsyncTask with Kotlin’s Coroutines. If you have any query regards this article, you may ask us. Additionally, please share your love by sharing this article with your friends.