Kotlin Anko Coroutines

Why Kotlin better than Java For Android Development
Why Kotlin better than Java For Android Development

Kotlin Anko Coroutines is utilities based on the kotlinx.coroutines library.

Using Anko Coroutines in your project

Add the anko-coroutines dependency to your build.gradle:

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

Listener helpers


If your asynchronous API does not support cancellation, your coroutine may be suspended for an indefinite time period. As a coroutine holds the strong references to captured objects, capturing the instance of Activity or Fragment instance may cause a memory leak.

Use asReference() in such cases instead of the direct capturing:

suspend fun getData(): Data { ... }

class MyActivity : Activity() {
    fun loadAndShowData() {
  // Ref<T> uses the WeakReference under the hood
  val ref: Ref<MyActivity> = this.asReference()

  async(UI) {
      val data = getData()
      // Use ref() instead of this@MyActivity

    fun showData(data: Data) { ... }


You can easily execute your code on the background thread using bg():

fun getData(): Data { ... }
fun showData(data: Data) { ... }

async(UI) {
    val data: Deferred<Data> = bg {
  // Runs in background

    // This code is executed on the UI thread

In next article we discuss about Anko Layout.

Share your thoughts

Loading Facebook Comments ...
Loading Disqus Comments ...