Use Anko of Kotlin in Android to run background tasks (KAD 09) and kotlinanko
By Antonio Leiva
Time: Jan 19,201 7
Link: https://antonioleiva.com/anko-background-kotlin-android/
Anko is an Android library developed by Jetbrains using Kotlin. It can be used in many different aspects.Its main feature is to useDSLCode Creation View.
Although this may be interesting, the fact is that I have been using XML for a long time. So we haven't tried this feature too much.
In fact, it has other very useful features, which is why I want to tell you today that it is very cool.
Anko is used to execute background tasks
In Android, the main thread is often blocked by operations other than it.
From several frameworks (such as AsyncTask or Loader) to libraries,There are thousands of options. Some use RxJava for this purpose.
All valid options have their own advantages and disadvantages.
But among themMost of them are very complex., Even if the implementation is simple to do some heavy tasks outside the main thread.
Anko uses the Kotlin capability to provide a simple and lightweight solution to release the main thread from a long running task.
Add dependency in your project
First, the dependency is included.
Like Anko doing many things, the database scale is out of control. Therefore, you need to decide to split it.
For example, you only need to import:
1 compile 'org.jetbrains.anko:anko-common:0.9'
Run the task in the background thread
If you remember, in the previous article, we implemented a very basic doAsync function that can run in the background. Anko can perform one or more tasks by executing context. We will see an example later.
Now the code is very similar to this:
1 doAsync {2 var result = runLongTask()3 }
But how do we return to the main thread?
Back to main thread
This is very simple. You only need to add the uiThread code block inside doAsync, which will run the main thread.
1 doAsync {2 var result = runLongTask()3 uiThread {4 toast(result)5 }6 }
Toast () is another useful function provided by Anko, which simplifies the method for displaying messages in the APP.
But what is important is the uiThread part. This is running in the main thread.
Do you know? If an Activity calls doAsync, The uiThread code will not be executed if the Activity is extinct (isFinishing returns true. In this way, we avoid AsyncTask errors or other callback functions that do not pay attention to the activity lifecycle.
Conclusion
As you can see, Anko provides a group of shared programs to simplify our work in writing Android apps. There are many others, such as dialog creation or database maintenance, which I can read in the following articles.
However, if you really want to use Kotlin to create an APP, you can start with my free guide,It will help you useKotlinCreate your first AndroidProject.