Read More
Read now

Corountines vs Thread in Android

Save

Coroutines are like threads executing work concurrently. However, coroutines are not necessarily associated with any particular thread. A coroutine can initiate its execution on one thread, then suspend and continue its execution on a different thread. Kotlin coroutines are not managed by the operating system; they are a language feature. Kotlin coroutines have been stable since Kotlin 1.3.

How are threads different from Coroutines?

Let’s suppose that we have a quad-core CPU — a CPU which has 4 cores.

Imagine that our CPU is just like a factory where each CPU core corresponds to a worker. Under this scenario, there are four workers, representing the individual cores of the processor.  the whole process is controlled by the operating system. Threads are like sequences of commands given to the CPU cores. But coroutines not directly interact with CPU cores they are just function and can be used to perform the asynchronous task.

Creating thread is simple but to update UI from it we need a handler class. But in coroutines, there are dispatchers we can use them to perform long-running operation off the UI thread or we can update UI thread directly with using MainCoruntinesDispatcher.

Let’s look into Coroutines example:

 

All commands of the program are executed sequentially since is a blocking call. The first function starts on the main thread, then the thread is blocked for 1 second. Once the function is finished, the thread will be available for the second function to start.

Since delay() is a suspending function, calling it from the first function results in a non-blocking suspension, and the thread is released to perform another task. This is how we can use to perform an asynchronus operation using coroutines.

 

 

 

 

 

. . .

Leave a Comment

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


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home