...

/

Coroutines Under the Hood

Coroutines Under the Hood

Learn to use coroutines for non-blocking code and the state design pattern to divide function execution into multiple stages..

We'll cover the following...

We know the following facts:

  • Coroutines are like lightweight threads. They need fewer resources than regular threads, so we can create more of them.
  • Instead of blocking an entire thread, coroutines suspend themselves, allowing the thread to execute another piece of code in the meantime.

But how do coroutines work?

As an example, let’s take a look at a function that composes a user profile:

fun profileBlocking(id: String): Profile {
// Takes 1s
val bio =
fetchBioOverHttpBlocking(id)
// Takes 100ms
val picture =
fetchPictureFromDBBlocking(id)
// Takes 500ms
val friends = fetchFriendsFromDBBlocking(id)
return Profile(bio, picture, friends)
}
Building a profile with fun and blocking code

Here, our function takes around 1.6 seconds to complete. Its ...