1. 程式人生 > >Anko to run background tasks with Kotlin in Android (KAD 09)

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.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

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:

1 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:

123 doAsync{varresult=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.

123456 doAsync{varresult=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.

But if you really want to take the plunge and start creating Apps with Kotlin, then you can start with my free guide, that will help you create your first Android project using Kotlin.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

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

How to create own operator with python in mxnet?

處理 需要 調用父類 rgs rop 數據類型 賦值 創建 recipe 繼承CustomOp 定義操作符,重寫前向後向方法,此時可以通過_init__ 方法傳遞需要用到的參數 1 class LossLayer(mxnet.operator.CustomOp):

在pycharm中以管理員身份運行/調試腳本(How to run / debug programs as root in Pycharm)

不想 http 設置 pan programs 額外 smi pytho 參考 如果想要在pycharm中以root的身份運行python腳本,因為pycharm本身好像沒有這個特性,目前只能通過一些額外的手段來實現。思路就是讓pycharm以root身份執行python編

Take Realm to the next level with Kotlin

When someone asks me what I like the most about Kotlin, I find it hard to highlight a single feature. Data classes, lambdas, type inference, delegate

dotnet core系列之Background tasks with hosted services (後臺任務)

 這篇簡單講asp.net core 中的後臺任務 用到的包: Microsoft.AspNetCore.App metapackage  或者加入 Microsoft.Extensions.Hosting   一. Timed background tasks(定時

how to mount /system as read/write in android? 在除錯RK3288的OV2718的驅動時,需要remount /system目錄為rw以push檔案到/system/lib/hw目錄下,常規的是用adb登入上去後以root許可權執行mount -o re

在除錯RK3288的OV2718的驅動時,需要remount  /system目錄為rw以push檔案到/system/lib/hw目錄下,常規的是用adb登入上去後以root許可權執行mount -o remount,rw /system即可,然而在拿的新板子後這麼做失效了,於是百

How To Communicate Between Fragments and Activities in Android

Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previ

Handling & Validating User Input (& More) with sauciness in Android with Java

Things you’ll needDesign Support Library (TextInputLayout & TextInputEditText)ValidComponent Annotation (We’ll create it)Component Validator & Othe

How to Correctly Use SQL's like in Android

Yesterday I stumbled about the correct usage of the LIKE-statement in conjunction with selectionArgs. My first attemp

How to Correctly Store App-Specific Files in Android

Christophe Versieux (Waza_be) posted a rant about android developers' bad habit to store files directly on the root o

Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

It had taken me too long to write an article to one of the most important parts of Kotlin: the treatment of nullity. Tony Hoare, the creator of the i

How To run OAI eNB (No S1) with USRP X310(1)

end analyze cep tel linu lin mod str reat How To run OAI eNB (No S1) with USRP X310 1.Things need to be done 1.1 Install Ubun

Configure Tomcat 7 to run Python CGI scripts in windows(Win7系統配置tomcat服務器,使用python進行cgi編程)

it is ram -i cto director 進行 comment XML env Pre-installation requirements1. Java2. Pythonsteps1. Download latest version of Tomcat (Tomc

啟動Apache出現錯誤Port 80 in use by "Unable to open process" with PID 4!

pre 找到 with pen nbsp art configure style post 22:15:30 [Apache] Problem detected! 22:15:30 [Apache] Port 80 in use by "Unable to open

Spring Boot 利用插件構造QueryDSL語句時報錯:You need to run build with JDK or have tools.jar on the classpath.If this occur....

cli roc ini文件 The 解決 tps proc 自己 沒有 You need to run build with JDK or have tools.jar on the classpath.If this occures during eclipse buil

Gulp error in WebStorm: Failed to list gulp tasks

ble mov AS solution AI ebs with sam set I have the same problem with webstorm after install a updated version of node. The solution for m

How to setup a slave for replication in 6 simple steps with Percona XtraBackup

second path binlog ica direct isam fetch owin value Data is, by far, the most valuable part of a system. Having a backup done systema

You need tcl 8.5 or newer in order to run the Redis test.

You need tcl 8.5 or newer in order to run the Redis test. 安裝Redis,執行make test的時候出錯: You need tcl 8.5 or newer in order to run the Redis test make: *** [te

How to detect and extract forest areas in a aerial image map with the knowledge of DIP

Signal processing is a common subject in electrical engineering, communication engineering and mathematics that deals with analysis and processing

spring boot 新建專案後執行有錯To display the conditions report re-run your application with 'debug' enabled.

錯誤: ror starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2018-10-19 20:42:26.6