Kotlin Coroutines for Android - The ABC’s

Sarah Maher
4 min readSep 5, 2021

--

If you have been around Kotlin enough, chances are you heard about coroutines. In this series we’ll be learning what are coroutines, and how to utilize them in our Android projects.

What is a “Coroutine” ?

A coroutine is a function that can pause its own execution to be resumed later. You can think of coroutines as light-weight threads.
Let’s put this in a real life example!

let’s assume we have dishes to do and also a cake to bake. Normally we will consider each chore as a task that we complete and then proceed to the next one, right?

Not the most optimal way in real life! In real life we may want to start the cake mixing and put it in the oven, then we shift to our dishes till the oven timer rings and go back to the baking task.

Looking at how we shifted the work from Cake-Task .. Dishes-Task .. Cake-Task and so on, we utilized any waiting time in doing another task, This is exactly what coroutine is all about.

Why coroutines for my Android project?

As a developer we should introduce a technology with a convincing argument specially when we work on an existing project.
Usually we use coroutines because :

  • They are light-weight.
  • Built-in cancellation support.
  • Lower chances for memory leaks, through structured concurrency.
  • Jetpack libraries provide coroutines support.

Hopefully each of those will be clearer by the end of the series.

Suspend Keyword

Suspend is a keyword that indicates that a function can be paused and resumed.

suspend keyword in action

Any function that is marked as suspend can only be called from other suspend function or a coroutine scope. we will get what coroutine scope next.

Coroutine scope & structured concurrency

You can think of coroutine scope as the racing track that our coroutines runs in. no racing car can run outside of it. there are multiple coroutine scopes that we’ll be learning about later like (launch, Async, etc).

Since all coroutines need to be triggered of some coroutine scope, this means the lifespan of the scope is tied to the coroutines started on it.
this means that no coroutine get lost or leaked.

An outer scope cannot complete until all its children coroutines complete and hat any errors in the code are properly reported and are never lost.

this is exactly what structured concurrency mean, and this is the reason that we mention Fewer memory leaks as a coroutine feature.

Coroutines != Background thread

You may get the idea that coroutines run on background thread by default, that’s actually wrong. Coroutines run on based on the dispatcher by default and suspend doesn’t mean background thread.
what if I wanted to run a coroutine on another thread? when need to work with something called Dispatchers.

Dispatchers, Dispatchers..

A CoroutineDispatcher is what determines what thread or threads the corresponding coroutine uses for its execution. The coroutine dispatcher can limit a coroutine execution to a specific thread.

Kotlin provides the following dispatchers that you can use:

  • Dispatchers.Main : this dispatcher is used to run a coroutine on the main Android thread. This should be used only for interacting with the UI and performing quick work.
  • Dispatchers.IO : this dispatcher is optimized to perform disk or network I/O outside of the main thread. Examples include reading from or writing to files, and running any network operations.
  • Dispatchers.Default :This dispatcher is optimized to perform CPU-intensive work outside of the main thread. Example use cases include sorting a list and parsing JSON.
  • Dispatchers.Unconfined: it executes coroutine immediately on the current thread and later resumes it in whatever thread called resume. It is usually a good fit for things like intercepting regular non-suspending API or invoking coroutine-related code from blocking world callbacks.

IO Dispatcher vs Default Dispatcher

Dispatcher.Default has limited to the number of CPU cores while Dispatcher.IO has an elastic thread pool with a configurable max size, who are expected to spend most of their time in a non-runnable state, awaiting the completion of an IO operation.

The idea is that the IO dispatcher spends a lot of time waiting (IO blocked), while the Default dispatcher is intended for CPU intensive tasks, where there is little or no sleep.

Whats next?

This is only the starting stone for our road to master coroutines. You are encouraged to try play around concepts that we learned in this article before proceeding in reading more articles.

Each of the following articles can be checked separately or as a series :

--

--

Sarah Maher

An Engineer Who Keeps talking about Android || Women In Tech || Find me on LinkedIn : https://www.linkedin.com/in/sarah-maher-awad/