EXAMPLE OF CRITICAL ANALYSIS ESSAY

write my research paper THIS IS HOW TO WRITE AN EFFECTIVE RESEARCH PAPER This Is How To Write An Effective Research Paper The professional writers have expertise working underneath pressure with…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Coroutines in Kotlin

Kotlin has introduced a new way of writing asynchronous and non-blocking code. In this article, we will cover the basics of the coroutines.

To understand this, let's first try to understand how synchronous and blocking task looks like:
Blocking and synchronous basically mean the same thing. For eg: when you call an API, it hangs up or blocks the thread until it has some kind of response and returns it to you.
Non-blocking means that if an answer can’t be returned rapidly, the API returns immediately with an error and does nothing else. So we should have some other way to know whether the API is ready to be called (ie. to simulate await in an efficient way, to avoid the manual polling).
Asynchronous means that the API always returns immediately, having started a “background” effort to fulfill your request, so there must be some related way to obtain the result.

According to the official documentation of Kotlin:

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

In simple words, coroutines and the threads both are multitasking. But the difference is that threads are managed by the OS and coroutines by the users.
A lightweight thread means it doesn’t map on the native thread, so it doesn’t require context switching on processor, so they are faster.
The most interesting thing is that a thread can stop executing a coroutine at some specific “suspension points”, and go do some other work. It can resume executing the coroutine later on, or another thread could even take over. We will discuss suspension later in this article.

These are the functions to start the coroutine:
launch{}
async{}
The main difference between these two is that the launch{} does not return anything and the async{} returns an instance of Deferred<T>, which has an await() function that returns the result of the coroutine like we have future in Java. and we do future.get() in Java to get the result.
Let’s try to understand the coroutine with an example.
The first step is to add the following dependency to your build.gradle

Full program that uses launch:

We are using the delay() function that looks like Thread.sleep(), but it's not the same. The difference here is that it doesn't block a thread, but only suspends the coroutine itself. The thread is returned to the pool while the coroutine is waiting, and when the waiting is done, the coroutine resumes on a free thread in the pool.
If we try to use the same non-blocking delay() function directly inside main(), we’ll get a compiler error:

This is because we are not inside any coroutine. We can use delay with runBlocking {} as well, that starts a coroutine and waits until it's done:

runBlocking {} is different from launch as it actually blocks the thread until the things inside it are complete.

Suspending functions may suspend the execution of the current coroutine without blocking the current thread. For eg:
suspend fun delay(timeMillis: Long) {…}
This means that the code you are looking at might stop executing at the moment it calls a suspending function and will resume at some later time. However, it doesn’t say anything about what the current thread will do in the meantime.
It might go back to executing another coroutine at that point, and it could later resume executing the coroutine we left. All of this is controlled by how your suspending function is called by the non-suspending functions world.

Here is another coroutine builder called async which allows performing an asynchronous operation returning a value:

As we discussed earlier, async{} function returns a deferred value, unlike launch. In order to get the result of the deferred value, async returns a convenient Deferred object, which is the equivalent of Future or Promise. We can call await on this deferred value in order to wait and get the result.
await is not a normal blocking function, it is a suspending function. await() can not be called outside a coroutine, because it needs to suspend until the computation finishes, and only coroutines can suspend in a non-blocking way. So, we put this inside a coroutine.

Add a comment

Related posts:

18 Questions Your CEO Forgot to Ask When Building Your Website

Why are you always retrofitting and re-optimizing? Your CEO (or other decision maker) didn’t ask the right questions. You need to know how to build and promote a website from the ground up to be…

The Mystery Is

I was watching the candle this morning. The wick had somehow moved nearer to the front of the candle. The heat of the flame was able to melt the wax as I watched the side of the candle become…