Mastering Kotlin Coroutines In Android

Tram Ho

Handling asynchronous is an issue that any programmer must encounter. Today, let’s take a look at an incredibly powerful asynchronous handling framework in the Kotlin language. Those are coroutines.

For simplicity, coroutines are a way to write asynchronous code sequentially. Instead of creating a mess with callbacks, you can write the code once after all. Some of them will be able to suspend execution and wait until the result is ready.

1. What is Coroutines?

Coroutines is a combination of Co, which stands for Cooperation, meaning cooperation and Routines, meaning function . It can be understood that when the functions work together, we call it Coroutines .

Let’s understand it through the example below: Suppose we have 2 functions functionA and functionB

I will explain a bit: When we call functionA(1) functionA will do taskA1 and call functionB (1), continue functionB will do taskB and recall functionA (2) … and so on until taskB4.

The example above is an example of the mutual cooperation between functions together. In Kotlin Coroutines, cooperation like the example above can be done very easily without using when .

So we have the original picture of Coroutines, right. It is a combination of functions. And there are endless possibilities that are opened with natural cooperation between functions.

Some possibilities are as follows:

  • It can execute a few lines of functionA and then execute a few lines of functionB and come back to actually a few lines of functionA … This will be very useful when a thread is in a state of doing nothing. . In this case, it may execute several lines of another function. This way, it can take full advantage of a thread. This collaboration helps the multitasking process.
  • It will allow writing the code asynchronously in a synchronized manner.

Coroutine will make multichreading easier.

Coroutine and thread have similarities are both multi- threaded. But another point is that the operating system’s thread is threaded and coroutine is by the user as it executes several lines of functionality by leveraging collaboration.

Coroutine is an optimization framework written on the actual thread by leveraging the collaborative nature of the functions to make it lighter than the thread but very powerful. So we can say Coroutine is a lightweight thread. This is because it is not associated with the original thread, so it does not require a context to switch in the processor, so they will be faster.

Why does it say Coroutines is not linked to the original thread? Coroutines it is available in many programming languages. Basically, there are 2 types of Coroutines:

  • Stackless
  • Stackfull The Kotlin language uses stackless coroutines . It means that coroutines do not have their own stack, so it is not associated with the root thread.

We can make a thousand coroutine, but it consumes very little performance. As for a thousand threads, that’s a big problem for the machine.

Understandably Coroutine does not replace thread. It helps as a framework for thread management.

2. Why do you need Kotlin Coroutines?

Let’s take a look at this example: We have an android application that has the following 2 functions:

  • Retrieve data from the server.
  • Display data on the application screen.

When executing fetchAndShowUser () above, it will fire a NetworkOnMainThreadException because the network is not allowed to call on the main thread.

To solve that, we have some ways to handle as follows:

  1. Using Callback: We execute code fetchUser () in background thread and retrieve data returned by callback.

  1. Using RxJava: This is how we can get rid of nested callbacks.

  1. Use Coroutines:

It looks a lot like synchronous code but it is actually asynchronous. Let’s find out how it did so below.

3. Step by step guide to deploying Coroutines in Android

First, let’s proceed to install Coroutines into the project: Add the following paragraph to the gradle file:

Now rewrite fetchUser function according to Coroutines:

Don’t worry, we’ll find out each of those confusing words below.

And the fetchAndShowUser () function will look like this:

The showUser () function we will keep the same.

Now is the time to explain the keyword concerns above:

  • Dispatchers: it helps Coroutines decide the workflow where the work must be performed. There are 3 main types that: IO, Default and Main. IO dispatcher is used to work with network and disk-related jobs. Default is used to handle CPU intensive tasks. Main is no stranger to the Android UI thread. To use them, we need to declare them as async function. The async function will look like below:

  • suspend: suspend function is a function that can start, stop and continue.

Suspend functions are only allowed to be called from one coroutine or another suspend function. You can see an async function including a suspend keyword.

So fetchAndShowUser function can only be called from a suspend function other than a coroutine. We cannot make onCreate a suspend function, we need to call it from a coroutines like below:

What actually happened is:

The fetchUser () function will be implemented in the background thread and showUser () will run on the UI thread because we used Dispatchers.Main to launch it.

In Kotlin there are two ways to launch a coroutines:

  • launch {}
  • async {}

So what’s the difference between these two functions? That launch {} will not return anything and async {} returns an instance of Deferred <T>, it has an await () function to return the result.

Let’s explore it through an example: There is a fetchUserAndSaveInDatabase function like the one below:

Now we will use launch as shown below:

With fetchUserAndSaveInDatabase () function will return nothing, we can use launch.

But when we need to return results, we need to use async.

We have 2 functions that will return data as User as follows:

We do not need to add suspend keywords because we never call a suspend function from them.

Now, we can use async like below:

We fetch fetch from the background and wait for the result to return in the UI thread.

We now understand the difference between launch {} and async {}.

Another way to write an async that we don’t need to write await () is withContext ().

4. What are scopes in Kotlin Coroutines?

Scopes in Kotlin coroutines are very useful because we need to cancel the background tasks as soon as possible when an activity is canceled. Now, we will learn how to catch these types of situations.

Assuming our activity has a scope, jobs in the background should be canceled as soon as possible when the activity is canceled.

In Activity, we need to execute a CoroutineScope:

We will initialize the Job in onCreate ():

And destroy it in the function onDestroy ():

Now, we can get the following data:

So before the activity is canceled, the job will also be canceled if it is running because we have defined the scope.

When we need a global scope, also called an application scope, not an activity scope, we can use GlobalScope as shown below:

Here, even if the activity is called destroyed, the fetchUser function will still run because we have used GlobalScope.

This is exactly why Scopes in Kotlin Coroutines are so useful.

5. Exception handling in Kotlin Coroutines

Handling call rules that have another important topic. We need to learn.

When using launch We need to create an exception handler as shown below:

We will enclose the handler every time we call launch () {}

Whenever there is any exception in fetchUserAndSaveInDatabase, it will be caught by the handler we have added.

When used in activity scope, we can include an exception handler in the corountineContext as shown below:

And use the following:

When using async

When using async, we need to use try-catch to catch exceptions:

This is exactly how foreign handling can be expressed in Kotlin Coroutines.

Summary:

Coroutines will be an extremely effective solution in handling asynchronous Android programming Kotlin. Because of its simplicity, neatness and robustness. I am sure you will not be hard to grasp it. Looking forward to this article you will have an overview from coroutine overview.

Refer:

Share the news now

Source : Viblo