Coroutine context - Dispatchers

Coroutine context - Dispatchers

According to official documentation ,

Coroutines always execute in some context represented by a value of the CoroutineContext type, defined in the Kotlin standard library.

In the Android world , CoroutineContext is mostly Dispatchers which is a reserved thread for specific action to take place.

There are 4 Dispatchers

Dispatchers.Main

Runs the coroutine in the main thread which is UI thread in our android world.

Dispatchers .IO

Runs the coroutine in the IO thread which is used for Database operations, to do a network call or read and write a file .

Dispatchers.Default

Runs the coroutine in the Default thread which is used for heavy computation on the main thread like doing a 10,000 calculations on the thread.

Dispatchers.Unconfined

  • According to the official documentation ,

    As the name suggests unconfined dispatcher is not confined to any specific thread. It executes the initial continuation of a coroutine in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy.

Code

/**
* Dispatchers
 */
Log.d("Coroutines", "Main Thread -  ${Thread.currentThread().name.toString()}")
// launching Coroutine in Main thread
lifecycleScope.launch(Dispatchers.Main) {
  Log.d("Coroutines", "Dispatchers.Main Thread -  ${Thread.currentThread().name.toString()}")
}

 // launching Coroutine in IO thread
lifecycleScope.launch(Dispatchers.IO) {
  Log.d("Coroutines", "Dispatchers.IO Thread -  ${Thread.currentThread().name.toString()}")
}

// launching Coroutine in Default thread
lifecycleScope.launch(Dispatchers.Default) {
  Log.d("Coroutines", "Dispatchers.Default Thread -  ${Thread.currentThread().name.toString()}")
}

Output

07:58:47.079 D/Coroutines: Main Thread -  main
07:58:47.117 D/Coroutines: Dispatchers.IO Thread -  DefaultDispatcher-worker-1
07:58:47.117 D/Coroutines: Dispatchers.Default Thread -  DefaultDispatcher-worker-3
07:58:47.185 D/Coroutines: Dispatchers.Main Thread -  main

As we can see the ouput , the respective coroutines are launched in a specified thread policy mentioned with Dispatchers parameter in launch function

Please leave your comments to improve.

Happy Coding