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

Sam

03/19/2024, 9:17 AM
I'm finding the naming of
Dispatchers.Main
quite unintuitive 😞. In a simple Swing app, the main (initial) thread and the UI thread are two different things. I'm trying to write an article talking about the two, and I literally can't find a nice way to explain it.
Copy code
suspend fun main() {
  println(Thread.currentThread()) // "Thread[main,…]" <- obviously the main thread, it says so in the name
  withContext(Dispatchers.Main) {
    println(Thread.currentThread()) // "Thread[AWT-EventQueue-0,…]" <- UI thread
  }
}
Anybody got any suggestions for an intuitive way to explain it to newcomers? So far I'm stuck at "Dispatchers.Main runs code on the UI thread, which is not the same as the main thread, but it's called that because on Android it runs code on the main thread, which is usually (but not always) the same as the UI thread" 🤦😂 😭
👀 1
😆 5
rubber duck 3
I might just avoid the problem and use
Dispatchers.Swing
for my examples 😂
Actually that's not a bad idea... explain all the concepts using
Dispatchers.Swing
, and then explain that
Dispatchers.Main
can be used as an alias if you secretly wish Swing was Android
🤣 1
I think I'll do that
s

streetsofboston

03/19/2024, 1:56 PM
Not sure about the Swing dispatcher, but the Main dispatcher is implemented by each native platform (differs from Android, from Desktop, from iOS, etc). At least on Android, the Main dispatcher is sensitive to long running tasks/operations. If they are too long, exceptions can be raised to that effect (ANRs)
r

Robert Williams

03/20/2024, 10:19 AM
It's basically a coincidence/ implementation detail that Android's main/ UI thread is the same as Java/ kotlin's
main
thread because you can't actually write a main function on Android
So I'd say what you propose sounds fine but only use Dispatchers.Swing for the earliest examples and as soon as possible introduce Dispatchers.Main as a more cross-platform/ multiplatform friendly alternative and use it exclusively for future examples
👍 1