How to async in Kotlin

Sateesh Gandipadala
2 min readOct 3, 2017

--

This is my first post on Medium. I am so happy to share with you how I stopped worrying about async tasks after moving to Kotlin. I don’t want to write about how miserable it is to work on Android AsyncTasks and complication they add.

We’ll be using a library called Anko by Jetbrains. It has many useful utilities which makes an android developer’s life easier. One of them is doAsync. To use this extension function you need to add anko-commons to your build.gradle.

dependencies {
compile "org.jetbrains.anko:anko-commons:$anko_version"
}

After this you can call doAsync{…} from anywhere in activity. If you want to update UI thread after completing the task you just need to add uiThread{…} inside doAsync block. Basic syntax of doAsync is:

doAsync{

// do background task here

uiThread{
//update UI thread after completing task
}
}

Let me demonstrate how to use doAsync to check if the URL of a remote file is valid or not.

doAsync {
var
isValidUrl = false
val
cxn = url.openConnection() as HttpURLConnection
cxn.requestMethod = "GET"
cxn.useCaches = false
cxn.setRequestProperty("Cache-Control", "no-cache")
cxn.connect()
if (cxn.responseCode == HttpURLConnection.HTTP_OK) {
Log.d("Connection", "Success !" + cxn.responseCode)
isValidUrl = true
} else {
Log.d("Connection", "Fail !" + cxn.responseCode)
isValidUrl = false
}
uiThread {
if
(isValidUrl){
// do valid url stuff
}else{

}
}
}

Good thing about using doAsync is that you don’t need to worry about dying activities, because the uiThread block won’t be called if activity is not alive. Amazing right…???!!!!

Happy coding…

--

--