Learn about Kotlin Coroutines (P1)

Tram Ho

I wrote this article to share the knowledge I have learned about Kotlin Coroutines in the simplest view for those who are curious about it. If you understand what Kotlin Coroutines is and use it, your mission is successful ? . We will explore the following topics:

  • What is coroutines?
  • Why do you need Kotlin Coroutines?
  • Step by step implementation of Kotlin Coroutines in Android
  • Scopes in Kotlin Coroutines
  • Managing exceptions in Kotlin Coroutines

In part 1, I will talk about the first 3 topics to help people have an overview of Coroutines. Let’s prepare a cup of coffee, a focus and step on the first part

I. What is Coroutines?

Coroutines = Co + Routines

Here Co stands for cooperation , Routines means functions . In other words, Coroutines is the combination of functions (It means that when functions cooperate with each other, we call it as Coroutines). It’s still not clear, let’s see the example below. Suppose we have 2 functions, functionA and functionB

functionA:

functionB:

When we call functionA as shown below

Now functionA will execute taskA1 and pass control to functionB to execute taskB1

Next functionB will execute taskB1 and pass control back to functionA to execute taskA2 and so on.

What is the key takeaway after the above example? This is how functionA and functionB work together to run tasks .

  • With Kotlin Coroutines, the combination in the above example can be solved very easily without using when or switch case . The code above runs a few lines of functionA, then runs a few lines of functionB , then goes back to running a few lines of functionA and so on. With that in mind, it is really useful when a thread is in idle state (doing nothing), while on the same thread can execute another function, maximizing the advantages of thread.
  • Kotlin Coroutines will allow writing asynchronous code in a synchronized manner. We will talk about this later in this article. In short, Coroutines makes multitasking processing much simpler. It can be said that Coroutines and Threads are multitasking. But the difference is that Threads is managed by OS (operating system) and Coroutines is managed by Users. Coroutines are also called “lightweight threads” because they do not map to the native thread, do not require context when switching on the processor, so it is faster.

So what does “not map to the native thread” mean?

Coroutines exist in many languages. Basically Coroutines are divided into two categories:

  • Stackless
  • Stackful

Kotlin implements stackless coroutines – this means that coroutines do not have their own stack, so they do not map to the native thread.

You can now understand the definition below as written on the homepage kotlinlang.org :

One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine.

But remember Coroutines don’t replace threads, it’s like a framework to help manage threads

II. Why do you need Kotlin Coroutines?

Let’s take a simple common example in the Android application:

  • Retrieving User information from server
  • Display User information

When we call fetchAndShowUser , ide will throw the NetworkOnMainThreadException , which means that calling network is not accepted on the main thread. There are many ways to solve this problem, as simple as

  • Use Callback : Call fetchAndShowUser function on background thread and return the result to main thread using callback

  • Using RxJava : This way we can solve the nested callback (nested callback can be understood as simply waiting for the response of an api to get that response as a param for the next request).

  • Use Coroutines :

The code above looks synchronous, but actually it is asynchronous (asynchronous). It was unexpected right ? .

III. Step by step implementation of Kotlin Coroutines in Android

First, add the following two lines to the build.gradle file:

The fetchUser () function outlined above will now look like this:

Function fetchAndShowUser ():

Function showUser ():

Through the above code lines, we have two more new concepts to learn, namely Dispatcher and Suspend .

  • Dispatcher : Dispatcher helps Coroutines in deciding on which thread to get work done. Dispatcher can be divided into three types of IO, Default, and Main . IO Dispatcher is used to work with networks. Default is used to perform tasks related to the CPU. Main is the UI thread in Android. To use the Dispatcher, you need to call them inside the async function.
  • Suspend : The Suspend function is a function with states that are started, paused, and resume.

The Suspend function is only called from one coroutine or another Suspend function . We can see that the async function includes the keyword Suspend .

So fetchAndShowUser () can only be called from a Suspend function or coroutine. We cannot declare the Activity’s onCreate function as a Suspend function, if we want to use the Suspend function inside the onCreate () function, we need to call it from coroutine as follows:

showUser will run on the UI thread because I have declared Dispatchers.Main to run this function. There are two functions in Kotlin to start coroutines:

  • launch{}
  • async{}

This part will stop here, let’s look forward to the next part ? I will introduce the concepts of launch, async, and the remaining two topics in the next section

Reference: https://blog.mindorks.com/mastering-kotlin-coroutines-in-android-step-by-step-guide

Share the news now

Source : Viblo