Antonio Leiva
Time:Jan,
Original link:Https://antonioleiva.com/anko-background-kotlin-android/
Anko is an Android library developed by JetBrains with Kotlin, which can be used in many different ways. Its main feature is the use of DSL code to create a view .
While this may be interesting, the fact is that I have been using XML very well for a long time. So there's not much to try with this feature.
In fact, it has other very useful features, and that's why I'm telling you today that it's cool.
Anko for performing background tasks
In Android, the main thread is often blocked by operations outside of it.
There are thousands of options available from several providing frameworks (such as asynctask or loader) to the library. Some use Rxjava for this purpose.
All valid options have their own merits and demerits.
But most of them are very complex , even if it is easy to do some heavy tasks outside the main thread.
Anko leverages Kotlin capabilities to deliver simple, lightweight solutions that release the main thread from long-running tasks.
Add dependencies in your project
First, include dependencies.
As Anko do a lot of things, the size of the library is out of control. So you need to decide to split it.
For example, you only need to import:
1 compile ' org.jetbrains.anko:anko-common:0.9 '
Run a task on a background thread
If you remember, in the previous article we implemented a very basic Doasync function that was able to run in the background. Anko can use the execution context to accomplish one thing or another. We will meet later with an example.
Now, the code is very similar to this:
1 Doasync {2 var result = Runlongtask ()3 }
But how do we get back to the main thread?
Return to main thread
This is very simple. You only need to add the Uithread code block inside the 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 way we display messages in the app.
But the important thing is the uithread part. This is run on the main thread.
Do you know what it is? If an activity invokes Doasync, the Uithread code is not executed if the activity dies (isfinishing returns True). In this way, we avoid asynctask errors or any other callback functions that do not notice the activity life cycle.
Conclusion
As you can see, Anko provides a common set of programs that simplify our work when we write Android apps. There are many other things, such as the creation of a conversation or the maintenance of a database, which I can read in the next article.
But if you really want to take the risk of creating an app with Kotlin, you can start with my free guide, which will help you Create your first Android project with Kotlin.
Run background tasks with Kotlin Anko in Android (KAD 09)