Dispatchers in Kotlin Coroutines
Last Updated :
10 Sep, 2020
Prerequisite: Kotlin Coroutines on Android
It is known that coroutines are always started in a specific context, and that context describes in which threads the coroutine will be started in. In general, we can start the coroutine using GlobalScope without passing any parameters to it, this is done when we are not specifying the thread in which the coroutine should be launch. This method does not give us much control over it, as our coroutine can be launched in any thread available, due to which it is not possible to predict the thread in which our coroutines have been launched.
Kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// coroutine launched in GlobalScope
GlobalScope.launch() {
Log.i("Inside Global Scope ",Thread.currentThread().name.toString())
// getting the name of thread in
// which our coroutine has been launched
}
Log.i("Main Activity ",Thread.currentThread().name.toString())
}
}
log output is shown below:
We can see that the thread in which the coroutine is launched cannot be predicted, sometimes it is DefaultDispatcher-worker-1, or DefaultDispatcher-worker-2 or DefaultDispatcher-worker-3.
How Dispatchers solve the above problem?
Dispatchers help coroutines in deciding the thread on which the work has to be done. Dispatchers are passed as the arguments to the GlobalScope by mentioning which type of dispatchers we can use depending on the work that we want the coroutine to do.
Types of Dispatchers
There are majorly 4 types of Dispatchers.
- Main Dispatcher
- IO Dispatcher
- Default Dispatcher
- Unconfined Dispatcher
Main Dispatcher:
It starts the coroutine in the main thread. It is mostly used when we need to perform the UI operations within the coroutine, as UI can only be changed from the main thread(also called the UI thread).
Kotlin
GlobalScope.launch(Dispatchers.Main) {
Log.i("Inside Global Scope ",Thread.currentThread().name.toString())
// getting the name of thread in which
// our coroutine has been launched
}
Log.i("Main Activity ",Thread.currentThread().name.toString())

IO Dispatcher:
It starts the coroutine in the IO thread, it is used to perform all the data operations such as networking, reading, or writing from the database, reading, or writing to the files eg: Fetching data from the database is an IO operation, which is done on the IO thread.
Kotlin
GlobalScope.launch(Dispatchers.IO) {
Log.i("Inside IO dispatcher ",Thread.currentThread().name.toString())
// getting the name of thread in which
// our coroutine has been launched
}
Log.i("Main Activity ",Thread.currentThread().name.toString())

Default Dispatcher:
It starts the coroutine in the Default Thread. We should choose this when we are planning to do Complex and long-running calculations, which can block the main thread and freeze the UI eg: Suppose we need to do the 10,000 calculations and we are doing all these calculations on the UI thread ie main thread, and if we wait for the result or 10,000 calculations, till that time our main thread would be blocked, and our UI will be frozen, leading to poor user experience. So in this case we need to use the Default Thread. The default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers. Default and uses a shared background pool of threads, so launch(Dispatchers.Default) { ... } uses the same dispatcher as GlobalScope.launch { ... }.
Kotlin
GlobalScope.launch(Dispatchers.Default) {
Log.i("Inside Default dispatcher ",Thread.currentThread().name.toString())
// getting the name of thread in which
// our coroutine has been launched
}
Log.i("Main Activity ",Thread.currentThread().name.toString())

Unconfined Dispatcher:
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.
Similar Reads
Scopes in Kotlin Coroutines
Scope in Kotlin's coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. Kotlin CoroutinesScope is a term well used in the referred for the interface used for defining the Scope(lifetime and context
6 min read
Exception Handling in Kotlin Coroutines
Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
7 min read
Destructuring Declarations in Kotlin
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables corresp
3 min read
Suspend Function In Kotlin Coroutines
Prerequisite: Kotlin Coroutines on Android The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a
4 min read
withContext in Kotlin Coroutines
Prerequisite: Kotlin Coroutines on AndroidLaunch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is
3 min read
Kotlin vs Groovy: In-Depth Comparison
In the world of computer science, we have a bunch of programming languages that serve different and unique features. Among these languages, Kotlin and Groovy are both programming languages that run on Java Virtual Machine (JVM) offering compatibility with existing Java code bases. While both languag
8 min read
Comparator in Kotlin
In programming contexts, as there arises a need for a new type, there is also a major task of ordering the instances of a type. To compare two instances of a type we implement Comparable interface. However, since in ordering instances they must be compared automatically and also since the order can
5 min read
runBlocking in Kotlin Coroutines with Example
Prerequisite: Kotlin Coroutines on AndroidSuspend Function In Kotlin Coroutines As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI a
5 min read
Closures in Kotlin
According to Kotlin's official documentation "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time the closure was created" var sum = 0 ints.f
2 min read
Launch vs Async in Kotlin Coroutines
The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used
4 min read