Creating a thread
Kotlin has simplified thread creation so that it's a straightforward process and can be done easily. For now, creating a single thread will be enough, but in future chapters we will also create thread pools in order to run both CPU-bound and I/O-bound operations efficiently.
CoroutineDispatcher
It's important to understand that in Kotlin, while you can create threads and thread pools easily, you don't access or control themdirectly. What you do is create aCoroutineDispatcher
, which is basically an orchestrator that distributes coroutines among threads based on availability, load, and configuration.
In our current case, for example, we will create a CoroutineDispatcher
that has only one thread, so all the coroutines that we attach to it will be running in that specific thread. To do so, we create a ThreadPoolDispatcher
– which extends CoroutineDispatcher
– with only one thread.
Let's open the MainActivity.kt
file that was generated previously – it's in the main package of the...