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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun main() { runBlocking { launch { test1WithCoroutines() } launch { test2WithCoroutines() } } } suspend fun test1WithCoroutines() { println("Start coroutines test 1: ${threadName()}") delay(500) println("End coroutines test 1: ${threadName()}") } suspend fun test2WithCoroutines() { println("Start coroutines test 2: ${threadName()}") delay(1000) println("End coroutines test 2: ${threadName()}") } |
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.