Using Anko to run background tasks with Kotlin in Android

Using Anko to run background tasks with Kotlin in Android (KAD 09)

Anko is an Android library written in Kotlin by Jetbrains, that can be used for a lot of different stuff. Its main feature is to create views by code using a DSL.

Although this can be very interesting, the truth is that I got along very well with XMLs for so long. So I haven’t tried this feature much.

But it does have other very useful features, and the one I tell you today is quite cool.

Anko used to execute background tasks

The issue of getting out of the main thread to execute operations that can block is very recurrent in Android.

There are thousands of alternatives, from several offered by the framework (such as AsyncTask or Loader) to libraries. Some even use RxJava for this.

All are valid options, and all have their pros and cons.

But most of them are very complex just to achieve the simple goal of getting out of the main thread to do some heavy task.

Anko takes advantage of Kotlin power to offer an easy and light solution to free the main thread from long-running tasks.

Disclaimer: This article just wants to show what the power of Kotlin can allow. As of today, I wouldn’t use this mechanism for background tasks, I prefer Kotlin Coroutines instead.

Add the dependency to your project

The first thing is to include the dependency.

As Anko does many things, the size of the library got out of hand. So there came a time when they decided to break it.

For this example, you only need to add the following import:

implementation 'org.jetbrains.anko:anko-common:0.9'

Run the task in a background thread

If you remember, in a previous article we implemented a pretty basic doAsync function, which could run background operations. Anko is able to use the execution context to do one thing or the other. We’ll see an example later.

For now, the resulting code is very similar:

doAsync {
    var result = runLongTask()
}

But how do we get back to the main thread?

Returning to the main thread

It is also very simple. You just have to write a uiThread block inside the doAsync, and this will run on the main thread.

doAsync {
    var result = runLongTask()
    uiThread {
        toast(result)
    }
}

toast() is another useful function provided by Anko, which simplifies the way we display toasts in our App.

But the important part is that of uiThread. This runs on the main thread.

And you know what? If the doAsync was called by an Activity, the code of uiThread will not be executed if the Activity is dying (isFinishing returns true). This way, we avoid a recurrent error that usually happens with the AsyncTask or any other callback that does not pay attention to the activity lifecycle.

Conclusion

As you can see, Anko provides a set of utilities that will simplify our life when writing Android Apps. There are many others, such as dialog creation or database management, which we may look at in the following articles.

If all this passionate you as to me, I encourage you to sign up for my free training where I will tell you everything you need to learn about how to create your own Android Apps in Kotlin from scratch.

20 thoughts on “Using Anko to run background tasks with Kotlin in Android (KAD 09)”

  1. Thank you for this entries. For a beginner like me they are really usefull.

    Willing to read the next one 🙂

  2. Your tutorials are really awesome. Can you please add some example codes, so it will be more helpful for Kotlin beginners like me

  3. Sanoop Surendran

    Hi Antonio,
    Greatly appreciate you for putting such awesome tutorials.
    I just want to know that, your book KOTLIN for Android developers have this topic, ANKO?
    Hope to hear from you soon.

    1. Yeah, the example in the book uses Anko for several purposes, such as background tasks, data bases or coroutines. Thanks for you interest!

  4. Sanoop Surendran

    Thanks, Didn’t expected such a quick response :). Looking forward to study in detail with the help of your book.

  5. Although I couldn’t buy your book (I live in Iran), but I almost learned everything about kotlin from your blog. Thanks.

  6. Great article!
    I’m struggling on how to apply this in an app using Clean Architecture. When you want to switch between background and main thread, usually a ThreadPool is used and some classes are created for this (Executors, threadPools,…) which the UseCases or interactors needs to execute the background tasks and then post the result to the main thread.

    I was looking at your Bandhook-Kotlin app posted on Github and you used a JobManager Library, but it has not being updated in a while. I know this is kind of an old project, but i think it’s the same case of threads.

    So, my question is, by using this Anko functions (or maybe coroutines), can we get rid of this classes and achieve the same results?

    Thank you!

  7. I don’t know if they changed it or what but you need to use `activityUiThread` instead of `uiThread` if you want to

    >>If the doAsync was called by an Activity, the code of uiThread will not be executed if the Activity is dying ?>> >>(isFinishing returns true). This way, we avoid a recurrent error that usually happens with the AsyncTask or any >>other callback that does not pay attention to the activity lifecycle

  8. Thank you for the awesome tutorial.

    According to android suggestion, the use of ‘compile’ keyword is obsolete. Use ‘implementation’ instead.

    implementation ‘org.jetbrains.anko:anko-common:0.9’

    cheers and have a good day

  9. Hi, thank you for the nice article, it was really helpful! I still have one question – I would like to use doAsync in my app for getting data from room db, I use MVP model and I am not sure how I should use in that case. Can I do something like this:

    Activity:
    fun loadData() {
    doAsync{
    presenter.loadDataFromDb()
    uiThread { toast(“Data loaded correctly”}
    }

    Presenter:
    loadDataFromDb() {
    model.getData()
    }

    Model: //create instance of my db and fetch data

    Would it be correct logic? Thank you in advance for helping out!

    1. That’s an option, though I prefer not leaving the decision on how to do the thread change to the activity. The alternative would be to use a presenter method with a callback. You can see my MVP article for that.

      Though if you find a way so that your team is careful enough to start threads consistently in the activity, that’s the perfect point because that means that you’re doing all non-ui work in a background thread. The refactor of Plaid by Google is done like that using coroutines, and I think it’s an interesting approach. You can take a look too. Think I raised more questions than solutions, sorry!

Comments are closed.