How to use Anko to run background tasks with Kotlin in Android
Anko is a library created by the JetBrains team, which makes Android development quite easy with the help of many helper functions that abstract a lot of complexity and provides you easy-to-use methods. One such thing is to deal with background tasks. Using Anko, we can work with background tasks very easily. In this recipe, we will learn how to work with background tasks using Anko.
Getting ready
We will be using Android Studio 3.0 for coding purposes; ensure that you have its latest version. You need to add Anko to your build.gradle
file, as shown:
implementation "org.jetbrains.anko:anko:$anko_version"
How to do it…
Doing a task in the background is very easy in Kotlin. Let's take a look at the next example. In this example, we will make a network request (which is required to do in the background or else you will get a NetworkOnMainThread
exception); once the network request is complete, we will show the Success
message using toast...