https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Stephan Schroeder

05/12/2020, 8:30 PM
So I finished the Coroutines - Hands on course https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/05_Concurrency And the thing I don't understand is this
Copy code
To 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?
n

Nikhil Mule

05/12/2020, 10:25 PM
Hi you can refer this blog I think this might clear your doubt
z

Zach Klippenstein (he/him) [MOD]

05/13/2020, 3:08 AM
a) You generally don’t need to worry about that.
Dispatchers.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/1648
s

Stephan Schroeder

05/13/2020, 9:51 AM
@Nikhil Mule I don’t work on Android at all. Currently on JVM and maybe Multiplatform in the future. @Zach Klippenstein (he/him) [MOD] sounds good, thanks
5 Views