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

paulex

03/25/2020, 8:16 AM
Please, Without using Android, is there a way i can switch context to a main thread inside a launch {} ?
o

octylFractal

03/25/2020, 8:18 AM
it is the same way as on android -- unless you're not using JavaFX/Swing/etc., and in that case you would need to implement the MainDispatcher yourself to indicate to Kotlin which thread is your "main" thread
p

paulex

03/25/2020, 8:30 AM
Yeah, i'm neither using JavaFX or Swing... can you guide me on how to implement a main dispatcher perhaps a link will help.
@octylFractal
t

tseisel

03/25/2020, 8:31 AM
Since you can't dispatch back to the first thread (the thread that called the
main
function) on non-UI application due to the lack of an event loop, you could use
newSingleThreadContext()
to create a dispatcher to use as your main thread. Note that you'll have to block the first thread (with
runBlocking
and
withContext
, or using
launch
and awaiting on the resulting job), otherwise the program will terminate.
o

octylFractal

03/25/2020, 8:39 AM
https://gist.github.com/octylFractal/4fb0ff0fe7fb25cb26d173ba1b3fcbf1 is a small + quick sample for a main dispatcher that does dispatch back to the main thread
only issue being that it doesn't quit 😛 you probably already have some sort of event loop with an exit flag you can put in place of the
while
loop though
p

paulex

03/25/2020, 8:47 AM
Alright... That made me feel like a dummy 🤦‍♂️ . I'm disappointed at my efforts in coding, like how did you come up with that so quick, how did you know about
ArbitraryMainDispatcher
etc... What am i not reading right?
@octylFractal
o

octylFractal

03/25/2020, 8:49 AM
well, I just wrote
ArbitraryMainDispatcher
based on the
JavaFX
main dispatcher, and gave it
queue(Runnable)
as a stand-in for JavaFX's
Platform.runLater(Runnable)
. The main part is knowing that
MainCoroutineDispatcher
exists
p

paulex

03/25/2020, 8:51 AM
Alright, followed you on keybase.! thanks
👍 1
t

tseisel

03/25/2020, 8:53 AM
Don't feel bad about it @paulex, I thought I knew a lot about coroutines until I saw @octylFractal's answer. Let's learn from each other!
👍 1
💪 1
🤣 2
🤗 2
z

Zach Klippenstein (he/him) [MOD]

03/25/2020, 3:14 PM
The coroutines library already provides a binding of
Dispatchers.Main
for javafx, is there some reason you can't use that? https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-javafx/README.md
o

octylFractal

03/25/2020, 8:21 PM
z

Zach Klippenstein (he/him) [MOD]

03/25/2020, 9:40 PM
Oops, I missed the “neither”, my bad
2 Views