Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Introduction

As we saw earlier, to perform multiple tasks simultaneously, we need multiple control flows which requires multiple threads. Thread management i.e. creating a thread, switching between threads is a computationally expensive task. In Kotlin, we delegate this thread management task to the Coroutines API. Instead of managing threads, we work with Coroutines.

Coroutine is a control flow / computation that can be suspended without blocking a thread.

Coroutines are control flow that run on a Thread. Multiple coroutines can be scheduled on a single Thread. In the above “Multiple requests” example, multiple coroutines were launched in parallel, one for each request. Coroutines share the Thread efficiently such that when one coroutine suspends, another one starts executing on the same thread.

Suspend refers to the temporary pause of a coroutine.

Why would a coroutine pause? There are certain operations that require computation to pause for an indefinite amount of time. Take Network (HTTP) request for example. When we send a Network request, it is unknown as to when the response will be received. It maybe received in 100ms, 200ms, 300ms or may take even longer. The control flow is idle after sending the request and before receiving the response :

 request sent -> ...idle... -> response received
 

So after sending the request, control flow is paused or suspended. When one control flow (coroutines) is idle (suspended), another control flow can be executed to efficiently utilize computer resources. This is what Coroutines API does. We can launch (start) multiple coroutines (control flow) which will be efficiently executed by the Coroutines API on the multiple threads available to a process.

Let’s summarize this with the help of an example. Suppose we want to run the following program :

 fun main() {
		sendEmail()
		sendWhatsApp()
		sendNotification()
}
 

To save time, we want to execute all three tasks in parallel. For executing these three control flows in parallel, instead of directly using Threads, we use Coroutines. We launch (start) three coroutines, one for each task :

 execute on coroutine 1 : sendEmail()
execute on coroutine 2 : sendWhatsApp()
execute on coroutine 3 : sendNotification()
 

Then, Coroutines API efficiently executes these 3 coroutines on the multiple threads available to the process.