Coroutines Under the Hood
Explore how Kotlin coroutines operate as lightweight threads that suspend without blocking, allowing multiple concurrent operations to run efficiently on fewer resources. Learn how the suspend keyword transforms asynchronous functions into non-blocking code and how the Kotlin compiler rewrites these functions using a state machine design pattern to optimize thread usage and responsiveness.
We'll cover the following...
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 1sval bio =fetchBioOverHttpBlocking(id)// Takes 100msval picture =fetchPictureFromDBBlocking(id)// Takes 500msval 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 execution is completely ...