Stephan Schroeder
05/12/2020, 8:30 PMTo run the coroutine only on the main UI thread, we should specify Dispatchers.Main as an argument:
launch(Dispatchers.Main) {
updateResults()
}
I would have expected Dispatchers.Swing to be used here, it is available in the course's setup.
So a) under which circumstances is Dispatchers.Main equal to Dispatchers.Swing and
b) If I want to use a Dispatcher backed by a single Thread (to avoid concurrent access on some unsychronized code), if I'm in a situation where Dispatchers.Main is equal to Dispatchers.Swing , and I don't want to use the UI-Thread to be responsible, which Dispatcher do I use instead? (AFAIK Dispatchers.Default is backed by as many threads as the computer has Hyperthreads and <http://Dispatchers.IO|Dispatchers.IO> is very specific as well.) Is there something better than Executors.newSingleThreadExecutor().asCoroutineDispatcher() ?
c) assuming I'm not on the JVM (and using Executors is therefore not an option), what's the Kotlin Multiplatform solution to create your own CoroutineDispatcher with a specific thread-count?Nikhil Mule
05/12/2020, 10:25 PMNikhil Mule
05/12/2020, 10:25 PMZach Klippenstein (he/him) [MOD]
05/13/2020, 3:08 AMDispatchers.Main will be automatically set to whatever is appropriate for the UI framework you’re using. On the JVM, I believe it’s done via service loader (so if you depend on the swing support artifact, it will be bound to Swing)
b) If you want to avoid concurrent access in coroutines, don’t create a separate dispatcher, just use a Mutex, a Semaphore, or another technique that limits concurrency (like actors).
c) Multi-threaded coroutines on kotlin native is a work-in-progress without an ETA. There is a draft PR up for support here: https://github.com/Kotlin/kotlinx.coroutines/pull/1648Stephan Schroeder
05/13/2020, 9:51 AM