Using a UI dispatcher
In the same way that we used a CoroutineDispatcher
to run a thread in the background, we can now use one to preform operations in the main thread.
Platform-specific UI libraries
Given that there are many types of GUI applications for the JVM, Kotlin has separated some platform-specific coroutine functionality into libraries.
kotlinx-coroutines-android
kotlinx-coroutines-javafx
kotlinx-coroutines-swing
Notice that all these platforms have the same UI model that we talked about before, in which only the UI thread can create and update the views. So, these tiny libraries are simply a CoroutineDispatcher
that is implemented to confine coroutines to the UI thread.
Note
The Android library also adds support for some exception pre-handling at thread level that is specific to Android.
Adding the dependency
Now that we know which library we need, we will simply add it to our gradle file for the module, below the dependency for coroutines.
implementation "org.jetbrains.kotlinx:kotlinx...