Tomás Hanley

15th Oct 2018

Using Coroutines in your Android App

Why use Kotlin?

  • Kotlin is a better language for the JVM than Java

    • Really easy to get up and running

    • Simpler language than Java

    • Much safer than Java

      • No more NullPointerExceptions!

      • Streamlines the handling of null values

    • More more clean & concise than Java

    • 100% Interoperable with Java

      • Kotlin & Java classes can live side by side

Androids Main Thread

  • View Inflation

  • Measure and Layout

  • Draw

  • Lots more

Mobile Refresh Rates

  • 60Hz    -    16ms

  • 90Hz    -    12ms

  • 120Hz    -    8ms

We need async!

"Asynchronous or non-blocking programming is the new reality.

 

Whether we're creating server-side, desktop or mobile applications, it's important that we provide an experience that is not only fluid from the user's perspective, but scalable when needed."

How do we do async?

  • AsyncTask

  • Executors

  • Loaders

  • Future

  • Libraries (like RxJava)

  • Coroutines

Why Coroutines?

  • Essentially, light weight threads

    • A new Thread uses 1MB
    • A new coroutine uses in the 10s of kilobytes
    • Suspended coroutine calls are removed from the stack
  • A new way of managing background threads​

  • Convert async callbacks for long-running tasks into sequential code

  • Makes writing async code much easier

Coroutines vs RxJava

Coroutines can replace:

  • Single / Maybe / Completable

  • Not everything

  • There are some Rx coroutine wrappers

Demo

Coroutine Scope

  • For managing coroutine cancellation

  • Parent-child relationship between coroutines

    • Ensures that cancelling a parent will cancel all its children

Demo

Dispatchers

  • Controls where the coroutine is run

    • i.e. the threadpool

  • Dispatchers.Default

    • Num CPU cores threads
  • Dispatchers.IO

    • Min 64 threads
  • Dispatchers.Main

Dispatchers

withContext(Dispatchers.IO) {

    val result = queryDatabase().await()
      
}
  • withContext will run block in specified dispatcher

  • When finished the coroutine will continue on the previous dispatcher

  • Good way to switch threads briefly to handle expensive operations

  • Link to codelab in meetup page

  • Android Studio 3.2

  • Configure it to use Kotlin 1.3

Lets get started!

Using Kotlin Coroutines in your Android App

By Tom Hanley

Using Kotlin Coroutines in your Android App

  • 86