Coroutines Step By Step From Scratch — Part-1

Puneet Grover
5 min readJan 5, 2021

“Reading doesn’t put you to sleep… it makes you dream…”
― Nanette L. Avery

Hey developers 👋 First of all let me tell you that every mobile has refresh Rate of around 1 time in every 16 seconds Hence We’ve to see carefully to not do any long task on Main thread instead use Background thread for any long or intensive task otherwise impact will be very Poor So this is the Importance of Asynchronous Programming.

And Guess What? We have Coroutines for both Synchronous and Asynchronous Programming and I’m damn sure you will love it !

It introduce a new style of concurrency that can be used on Android to simplify async code. That’s it!

If You want to do Something on Different thread we can use AsyncTask, RxJava, Executors and Now we can use Coroutines. So Simple 😆

A Coroutines can be Introduced as a sequence of well managed Sub Tasks. To Some extent Coroutines can be considerd as a Light weight thread

Do Remember that Threads are not equal to Coroutines

Any of the thread can have many coroutines, It’s just like a separate process running on a thread. A Coroutine can be switched between threads. A coroutine can be suspended from one thread and resumed from another thread

Benefits of using Coroutines is Simple, Very Efficient, Fast to Implement and Code looks much Cleaner and Neat + of course no callback hells and blocking states

Let’s dive in to each to see how coroutines can help us structure code in a cleaner way!

STEPS TO CREATE COROUTINE:-

Few Steps and Your Coroutine concept will be clear, Believe me ✌️

  1. In Order to use Coroutines we need to have Dependencies at App level. You can find that here — http://github.com/kotlin/kotlinx.coroutines
  2. Let’s Start with Coroutine Scope — An Interface that provides scope of Coroutine. Coroutine Scope requires Context i.e All the coroutines going to start within this scope will be run on this Context
  3. So if we want some code to run on Background thread We’ll have to pass Dispatchers.IO in this context
  4. To Start the coroutine we’ll have to launch it, we call it as Coroutine Builder

Don’t worry I will tell about every term like Scope, Dispatchers, Coroutine Builder later in detail Meanwhile Have a look on example

CoroutineScope(Dispatchers.IO).launch{
// any background work you want to perform
// like Download some user data
}

And It’s Done! Congratulations, You’ve created your first Coroutine, Yohoooooo! Isn’t it Amazing, Neat and Clean, a Simple way of doing Asynchronous programing as compared to others ?

I know you might have lots of questions like Dispatchers, Scope, Coroutine Builder etc. Let’s study about them first

Scope, Dispatchers and Builders

In an app we can launch many coroutines, can be in 100’s running at the same time But by default coroutines don’t help us to keep track of them. If we don’t manage them very carefully there can be coroutine leaks in the memory.

But Luckily 😅 for us, Kotlin programming language creators has already fixed this problem. In Kotlin Coroutines We have to must start All the Coroutines within a Scope.

Using the Scope properties we can easily track coroutines, cancel coroutines, handle errors or exceptions thrown by the coroutines

BORED 💁? But I hope It was Worth Studied. Let’s Learn these above terms One by One

SCOPE :-

Scope defines where are coroutines should run. We have GlobalScope, CoroutineScope. GlobalScope is used to launch Top level Coroutines which are operating on the whole application lifetime

CONTEXT OF SCOPE :-

Here Dispatchers.IO is the context of our Coroutine.

CoroutineScope(Dispatchers.IO)

In example above we have only used Dispatchers. We can use name of job instance also with Dispatchers as context of scope like this. Don’t worry we will study about Job in next Part. Meanwhile you can remember that Job is used to Track Coroutines or Cancel Coroutines explicitly. Hence context can be combination of both

Context = Dispatchers.IO + job

DISPATCHERS :-

Dispatchers describes the Kind of thread where Coroutines should be run. We have many dispatchers to serve different purpose/or to work on different threads

Dispatchers.Main -> Coroutine will run in the Main thread
Dispatchers.IO -> Coroutine will run ia Background Thread like to work with Local db, Communicate with network etc
Dispatchers.Default -> For CPU Intensive task such as Sorting a list etc.

It is Recommended that Kotlin Coroutines Should always start from Main Thread and then Switch to Background thread

Don’t worry Bit More Study and You will work on Coroutine like a Pro😃

COROUTINE BUILDER

CoroutineScope(Dispatchers.IO).launch

Here launch is the Coroutine Builder, Actually It’s an extension function of Coroutine Scopes which are used to launch a new Coroutine.

There are four Main Coroutine Builders:-

  1. launch
  2. async
  3. produce
  4. runBlocking

LAUNCH ->

Launches a new coroutine without blocking the current thread. It Returns an Instance of Job But Not Result as any return value

ASYNC ->

If we want to get result as return value use Async Coroutine builder. It also allows us to launch coroutine in Parellel and without blocking the current thread. It returns an Instance of Deferred<T>.
We need to invoke await() to get the value
In Android we use these two — Launch and Async most of the times. But we also have produce and runBlocking Coroutine Builders available

PRODUCE ->

Produce builder is for coroutines which produces a stream of elements. Returns an instance of Receive channel.

RUNBLOCKING ->

The Coroutine created using this will block the thread while the coroutine is executing. We use this Builder mostly for Testing purposes. It returns a result of Type T.

We will learn about other AWESOME and AMAZING things of Coroutines like Suspend functions, ViewModelScope, AsyncAwait, withContext in more detail in Next Part. and I know you are excited to learn more about it. Stay Tuned Guys!

So How was it ? Simple Isn’t it?

Thanks Everyone, I hope you learned something from this Article

Show your love by sharing this blog with your fellow developers.

Subscribe to My Youtube Channel for more such Videos! 🤩

Coroutines by CodingWithPuneet

Happy Coding!

Also, Let’s become friends on Linkedin, and Medium

--

--

Puneet Grover

Android Team Lead (Senior Consultant) @Deloitte USI | Google Certified Android Dev | Java | Kotlin | Blogger | Sometimes Youtuber