Asynchronous ProgrammingKotlin

Kotlin Coroutine can be a friend

Kotlin Coroutine

When we first glance at something new, we tend to loose attention and most of the times we ignore.

If that same new object is seen by a child, he/she gets curious and applies even more attention to it. If you have ever accompanied a kid, you might have observed the set of questions, which can boggle your mind. That clearly depicts the urge of learning, which unfortunately has been lost in majority.

Same thing happens even when we call ourselves experienced or professionals. Unfortunately, we tend to ignore the stuff which is not recorded in our brain before.

I did the same thing with Kotlin Coroutine. I saw and ignored, so quickly that it never existed.

Later, when I started doing Kotlin programming, I had to perform network operations with my server. I tried to look for the ways to perform  Asynchronous tasks. I looked at different options and finally returned to Kotlin Coroutine. 

Honestly, when I gave that required attention, I find it to be a friend. The advantages of Coroutine were really impressive.

With this post I will try to explain Coroutine, so that you can quickly integrate this into your live project.

Let’s begin…

I will be using some real world scenarios to first understand the use case.

EXAMPLE 1 : You went to a hotel and receptionist has asked for your name. Now, that can be treated as a prompt action and receptionist may not need to wait for you to figure out your name.

It is a ‘synchronous‘ call. This can be achieved using simple method where coroutine or ‘asynchronized’ task may not be required. 

EXAMPLE 2 : You visit a restaurant and order for a cup of hot tea with sandwich.

Now, if we look at pantry. There can be n-number of orders to be processed by chefs. If we think of chef’s as threads running to execute or prepare for the incoming orders. It should be processed based on the priority set for different orders. 

And, in a restaurant there can be limited number of chefs depending upon the business or the customer base. Similarly, there can be limited number of threads which can be consumed by an application at any particular time.

Lets come back to your order, “a hot cup of tea with sandwich”, which means before delivering your order, chef who is preparing for your tea needs to wait for sandwich to get prepared or vice-versa, there will be a callback before final delivery, this process can be treated as asynchronous.

This situation explains us the concept of multithreading 

To achieve all of this using Kotlin, Coroutine is going to be a friend of yours.
You already know the scenario. Let’s understand how it works?

If you have already heard about Threads, Tasks, Executors, Callbacks and more…, simply forget it.
Yes, you assumed it correctly, all of this is not required, because, Coroutine is going to do this for you.

Lets understand what Coroutine can do :

1. The coolest thing, GETTING ASYNCHRONOUS TASKS DONE AS IF YOU ARE DOING IT SEQUENTIALLY.

You just need to put suspend keyword before your method and it becomes asynchronous.

2. Coroutine is Lightweight.
3. Coroutine provides more control over your long-running operations.
4. This may be another surprise to you, as it was for me. Many Coroutines can run in a single thread.


Lets understand Coroutine with the help of a use case :

We will use Coroutine in our program to validate input credentials from server. To identify if the user has the access for any particular feature.

Just go through the source code snippet attached below : 

suspend fun fetchCredentials(): String {
    // Makes a call to local database
    // Validate User
    // Send credentials only if the validation succeeds
    return credentials
}
suspend fun fetchData(): Token {
    // makes a request and suspends the coroutine
    return suspendCoroutine { /* ... */ } 
}
fun pullData(query: String) {
    launch {
        val credentials = fetchCredentials()
        val result = fetchData(credentials, query)
    }
}

In the example above, fetchCredentials() is the suspend method which contains the source code to perform long running network operation and returns JSON String in the response.

I am using this snippet to help you understand the use case, adding source code to make actual server calls is out of scope for this tutorial and may be distracting.

Let’s understand what each keyword means and what to expect from them :

suspend Keyword

suspend keyword indicates that the method can suspend the execution of the given operation.

Create simple method and put suspend keyword before the name. 
Doing so, makes your function appropriate for long-running operations or to perform asynchronous tasks.

launch Keyword

Coroutine methods needs to be called within the scope, Scope may sound another strange keyword, but it has very nice use case.

Scope is used to handle your long-running operations depending upon your requirements. You might need your operations to run within the boundaries of the life-cycle of the activity or the application.

Lifecycle of a coroutine method :

1. Keep your long running operation active till your application is alive

This can be achieved using GlobalScope.launch keyword.

Below code snippet will keep the operation running till the application is alive.

fun pullData(query: String) {
    GlobalScope.launch {
        val credentials = fetchCredentials()
        val result = fetchData(credentials, query)
    }
}

2. Keep your long running operations active till your current activity is alive

This can be achieved using launch keyword.

Below code snippet will keep the operation running till current activity is alive.

fun pullData(query: String) {
    launch {
        val credentials = fetchCredentials()
        val result = fetchData(credentials, query)
    }
}

Coroutine also helps you write a clean code and deals with all the mess of memory leaks.

Conclusion

The simplicity coroutine has offered helped me to perform long-running operations in a easy way.

To get you quickly started, I have tried to keep this tutorial short without adding too much of details.

If you need understand it from depth, please check this link here.

If you haven’t tried the ‘Code Generator’ as yet, or if, you feel lazy while writing the source code as do I. This tool here might be of use to you.

Please share your comments, I would love to hear!

Don’t miss to subscribe, I will be sharing more contents on software programming practices.

0

6 thoughts on “Kotlin Coroutine can be a friend

Leave a Reply

Your email address will not be published. Required fields are marked *