The beginner's guide to Kotlin coroutines on Android (PART 1)

toluwani ogunsanya
2 min readSep 12, 2018

--

“white and brown yarn in basket e” by Kelly Sikkema on Unsplash

What is a coroutine?

A coroutine is a computation or a process that can be suspended without blocking a thread.

For example:

Let’s say I take the high way when I’m going home from work. If I discover that I have a flat tire while driving, I would pull over to the service lane, replace my tires with the spare, and get back on the road.

But I moved to the service lane, and suspended my motion by stopping to change my tires; the cars (operations) on the main road (main thread) continued their motion. When I was done, I got back on the main road and continued on my journey. When I was on the service lane, I was a coroutine. :)

How do you start a coroutine?

The lambda functions launch {} & async {} both launch a coroutine. The coroutine is the body of launch & async. The next section will help you pick the appropriate coroutine launcher to use.

What’s the difference between launch and async?

launch just runs a coroutine and async returns a Deferred <T> object after it has executed a coroutine.

The return type of the last executed line in the coroutine will be T. You can wait for the result of the coroutine by using the await function in the Deferred class, which returns a value of type T.

You can only call await on a deferred object in a coroutine

Want to update the UI with a coroutine?

This coroutine is launched with the UI context. Line 2 and 3 will run without blocking the UI, then 4 will run on the UI thread.

Suspend functions

Suspend functions are functions that may suspend the thread it is running on. A suspend function can only be run in a coroutine. If you have functions that may suspend the main thread when called, you should probably make them suspend functions. This way they can only run in a coroutine context.

Deferred functions

As mentioned above, async returns a Deferred object. When a coroutine is executed with async{}, it does not suspend its parent whether it is a coroutine or the main thread. When multiple async functions are called, they run concurrently. You can wait for all their results by calling await() on the returned Deferred object.

That’s it for today folks! PART 2 will be on Retrofit with coroutines.

--

--

toluwani ogunsanya

I am a Software Engineering student at the University of Ottawa. I love Android and Kotlin!