What is Coroutine, when, and how to use it?

Kaushik
3 min readJul 31, 2020

--

In today's discussion, we will learn about the kotlin coroutines basics, the basic reference to the general use of coroutines as coroutines is the largest topic in kotlin, I will be creating a series on kotlin coroutine. The basic idea of this post is: what is coroutine? and why developers should use it? and what is the benefit of using it? The post is mainly focused on the android developer but still, any other developer can get a reference from this post for coroutines. Let’s get started from basic.

Why we need it?

Programming is all about multithreading, handling many tasks at the same time, and providing results at the end. Developers often need to do work asynchronously with the use of thread in any programming language.

Let’s talk about an android thread, Android is a single thread model OS. If you want to perform any longer task in android, you must get off from the UI thread and perform it on separate background threat and send the background work result to the UI thread to update UI(Main thread). isn’t it so complex for beginners? I mean it’s 2020 anything could be possible? why not simple background task coding?

The magical solution.

Coroutine manages your long-running tasks in the background thread that might block the main thread and cause your app to freeze, it also providing main-safety, or safely calling network or disk operations from the main thread. Main thread-safety — Because coroutines can easily switch threads at any time and pass results back to the original thread, it’s a good idea to start UI-related coroutines on the Main thread. A coroutine is easy to read and add an exception, Fewer chances of memory leak.

There are three different threads in coroutines such as Dispatcher.Main, Displather.IO, and Dispatcher.Default. I will cover these three threads in my next discussion, for now, let's focus on the use of coroutine.

Let's take a look at the traditional approach for performing any longer task in android. Below is the kotlin example to make a network calls using callback style. In the below example, we are making a network call using callback style.

In the above code, we are calling a function from repository object which is makeNetworkWithCallbacks() which is expecting to pass a callback. When this function called, the program must wait to finish the onComplete() of the callback, if any error happens such as bad network requests or no internet, we will get an error message in our onError(). This is tedious, just imagine the scenario if we have nested request for callback? such callbacks are very confusing and it required a lot of manual error handling for each callback moreover high chance of getting many errors.

Let’s take a look above the same example using coroutines.

That’s it. That’s all and we are done with background work. Let’s take the above code piece by piece and learn. What viewModelScope is?

viewModel? -> it is scope. This scope tied to your viewModel.

launch? -> When creating coroutine from non- coroutine function or class. We must call launch on any scope of the coroutine.

There is a total of three scopes in coroutines for android. I will explain each scope one by one, before I start, let’s learn what is coroutines scopes?

All coroutines works are handled and managed by its scope. A scope controls the lifetime of coroutines through its job. When you cancel the job of scope, it cancels all coroutines started in that scope. So in simple work scope is the controller of coroutines and once the scope is canceled, all of the coroutines running inside that scope will be canceled.

Three different scopes of coroutines:

lifeCycleScope.launch{}: This scope tied to your activity or fragment, which usually runs on main thread of android. The scope will automatically end once the component lifecycle is destroyed.

viewModelScope.launch {}: This scope tied to your ViewModel and it launches coroutine which runs on the Main thread of Android. This scope end on onCleared () of ViewModel.

GlobalScope.launch{}: This scope is highly encouraged not to use until fully understanding the requirements of it. It tied to application context and only use when your task is attached to the application and you want to keep the instance of something to your application level.

So from above the most commonly used scope is ViewModel scope. The other important factor of using coroutines is changing the thread by simply passing the Dispatcher inside the scope function moreover, there are many more topics in this series. It will be in my next series of discussions about kotlin coroutines, till that time stay tuned and happy learning.

--

--

Kaushik

Enthusiastic Android developer, more interested in learning anything in android mobile, car, and watch.