Kotlin Coroutines: The threading worker - I

Kotlin Coroutines: The threading worker - I

Introduction

Welcome Kotlin people, this article series is going to be fun. Be prepared for the information shower alongside the joy ride in these articles.

Who is this for?

First things first - Who is this article for?

Well, for everyone who has a bit of multithreading knowledge and then knows about Kotlin as well. If you think you lack on any of those, no worries. Go through the article, this will surely give you an insight into the Coroutines and all you need to know about it.

See you in the Info pool.

What is a Coroutine?

A coroutine is an instance of suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.

A coroutine basically takes a block of code and executes it in an altogether concurrent manner, which is close to what a Thread does. But, are both the same? - NO

The coroutines can be seen as an over-powered thread, due to their capabilities. But, in actual it isn’t the same.

Coroutine vs Thread

Both the coroutine and thread are meant to perform blocks of code concurrently, but that doesn't make them the same. Basically, a coroutine will always require Thread to be executed, which clearly says that coroutine isn’t a thread.

A coroutine is quite a flexible Kotlin feature that allows to suspend its execution in the middle and resume later at any desired point.

The most exciting of a Coroutine feature is that they can easily switch their context from one thread to another. This was also stated in the Intro section of this article - It may suspend its execution in one thread and resume in another one.

This is why I have stated them as an over-powered thread. But, a point here to be noted is that even with those additional features, the coroutine is a light-weight thread.

Enough of talking, let’s dive into the code.

letTheFunBegin.gif

Our First Coroutine

Kotlin in itself does not include coroutines by default as part of the included inbuilt library, which is why we are first going to include the dependencies in the app’s build.gradle file:

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"

The simplest of coroutine can be started on GlobalScope (not a recommended practice, but just to demonstrate our first coroutine). We will be discussing different Scopes, later. Here’s the coroutine:

GlobalScope.launch {
    Log.i(TAG, "Coroutine running on ${Thread.currentThread().name}")
}
Log.i(TAG, "Current Thread is ${Thread.currentThread().name}")

Let’s run the app and check what does the logs has to say:

I/MainActivity: Current Thread is main
I/MainActivity: Coroutine running on DefaultDispatcher-worker-2

We also discussed that the coroutines can be suspended. We can do this by adding a delay:

GlobalScope.launch {
        delay(1000L)
    Log.i(TAG, "Coroutine running on ${Thread.currentThread().name}")
}
Log.i(TAG, "Current Thread is ${Thread.currentThread().name}")

Well, you might think that suspending a coroutine is the same as sleeping a Thread. But no, there is a difference and a huge one.

Suspending a coroutine vs Thread.sleep()

Let’s take a scenario, where we have 5 coroutines working on the same thread and we have to suspend 2 coroutines out of those 5. We can easily do that on the basis of our requirements as we have seen in the previous example. This is where the suspension of coroutine comes in handy.

On the other hand, if we require all the 5 coroutines to be suspended, Thread.sleep() will do the needful and will resume the coroutines at a later point.

Although the coroutines are started on another thread and running asynchronously, it will be cancelled if the main thread is exited.

Takeaway

  • Coroutines are considered light-weighted threads.
  • A Coroutine is a suspendable block of code that runs on a thread and can switch its context.
  • Coroutine library is not parcelled with Kotlin default library.
  • Suspending a coroutine is not the same as making a Thread sleep.

done-complete.gif

We will be digging into Coroutines a lot, further. Stay tuned for that. Thanks for reading this article! Leave a comment below if you have any questions. We will be back with an article, a step further into Coroutines. Till then, take care.