What is a coroutine?

Harjot Singh
3 min readOct 8, 2022

--

Before understanding what’s a coroutine, let’s first dive into some of the basic stuff which I’m sure you already know but duh…what’s the harm in going through it again.

Function…What’s that?
A sequence of instructions that takes some input and gives us output is called a function.

Thread..now what’s this?

Photo by amirali mirhashemian on Unsplash

No, not this one.
A thread describes in which context the function has to be executed.

If there’s no use of multi-threading in your application, you’re doing all the work on Main Thread a.k.a UI thread. However, this can lead to some problems 😅. Let’s see how :-

  • Network calls/ DB query/ Complex calculations: We often do network calls/ DB queries in the application. Here’s the scenario: A function has 3 instructions…Instruction 1, 2 and 3 to be executed sequentially on MAIN THREAD.

Say, Instruction 1 does it work and now we move to Instruction 2. Instruction 2 takes much longer time than what Instruction 1 takes. Now, Instruction 3 cannot be executed until Instruction 2 is complete since the instructions are executed sequentially. Since, Instruction 2 is taking a lot longer which would result in freezing the UI and the application might even throw an ANR dialog (App Not Responding)…like below:

Let’s say you or your app is lucky and this dialog doesn’t come i.e. Instruction 2 takes time but not that much that it throws this dialog, chances are the user would stop using your app, well of course it’s 2022…who has the time to wait that long on the screen.

For this reason, the Instruction 2 should be moved to other thread so that it does not block the main thread and the UX (User Experience) is way smoother.

I know…. I know what you’re thinking.
If multi-threading solves the problem then why the need for coroutine…actually what is a coroutine😫

Coroutines are just like threads but with some enhanced functionalities.

  1. Coroutines are executed within a thread! It can be considered as a light weight thread. The interesting part is your application cannot have gazillion of threads (it depends upon the CPU usage how many threads the application can handle) as it’d throw Out of Memory error but it can have many coroutines since it is light weight.

2. Coroutines are suspendable meaning you can execute some instructions…pause the coroutine in the middle of execution and continue whenever you want it to.

3. Coroutines can easily switch their contexts i.e. a coroutine started in one thread can switch the thread it’s running in.

Summarising, coroutines are light weight threads with better functionality.

Please do show your support by clapping for the blog. More blogs on this topic coming your way.
Until then happy coding!

--

--

Harjot Singh

Android Developer @HealhifyMe I lose my handwritten notes often...so now making sure I can find my notes easily :p