Kotlin Coroutines

Photo by Matt Duncan on Unsplash

Kotlin Coroutines

An asynchronous learning

ยท

2 min read

  • Coroutine is a computer program component that makes it possible to execute a block of code concurrently.

  • Coroutine works on a suspendable mechanism in which it suspends a piece of the program to execute on a separate worker thread while the rest of the program can continue with the execution which is known as Coroutine Continuation.

  • A coroutine is not bound to a specific thread, which means it can suspend execution on one thread and return results on another thread.

  • A coroutine is conceptually similar to a thread and is thought of as a lightweight thread.

Coroutine Continuation

When calling a function that returns some result along with continuation. This continuation gives the caller function a way to keep continued engagement.

Suspendable mechanism analogy

Chatting to someone on a topic and getting a phone call in the middle of a conversation. After finishing a call, you start the conversation where you left it earlier. Analogy breakdown:
Chatting to someone on a topic is one piece of code and getting a phone call is another piece of code. You suspend the conversation for a moment while you take a phone call on the same thread or a different thread. Upon this phone call finishes, you resume the conversation back where you left it earlier. Here is an example:

suspend fun main() {
    beforePhoneCallConversation()
    takePhoneCall()
    afterPhoneCallConversation()
}
suspend fun takePhoneCall() {}

fun beforePhoneCallConversation() {
    //Hello, How are you?
    //Hey, I am good.
    //Just a sec, my brother is calling.
}
fun afterPhoneCallConversation() {
    //Sorry, I had to take that call.
    //No problem.
}

Happy coding... ๐Ÿ˜Š

ย