https://kotlinlang.org logo
Title
r

Rainer Schlonvoigt

08/12/2019, 1:20 PM
is there a coroutines implementation for general JVM apps, e.g. a desktop application?
d

Dominaezzz

08/12/2019, 1:22 PM
Yes but for specific GUI frameworks. JavaFX, Swing, etc.
r

Rainer Schlonvoigt

08/12/2019, 1:24 PM
ouch
i am using coroutines for server things... did not expect UI to be involved
d

Dominaezzz

08/12/2019, 1:25 PM
Then why are you using
Dispatchers.Main
?
You should be using
Dispatchers.Default
,
<http://Dispatchers.IO|Dispatchers.IO>
and custom dispatchers if you see fit.
r

Rainer Schlonvoigt

08/12/2019, 1:30 PM
That solved it, thank you! 😄
l

louiscad

08/12/2019, 2:38 PM
If your app starting point is the
main
function, you can just start it that way:
suspend fun main(): Unit = coroutineScope {
    // app starts here, launch coroutines and all
}
d

Dominaezzz

08/12/2019, 2:49 PM
Might as well just use
runBlocking
, right?
l

louiscad

08/12/2019, 2:56 PM
suspend fun main
uses
Dispatchers.Default
in its
coroutineContext
, which is multi-threaded (at least 2 threads, configured for number of CPU cores), while
runBlocking
reuses the JVM single initial thread.
d

Dominaezzz

08/12/2019, 3:09 PM
Reuse appeals to me. Also this can be done.
fun main() = runBlocking(Dispatchers.Default) {
    // stuff
}
Although, that doesn't look much better that your initial example. So 🤷🏼 I guess.
l

louiscad

08/12/2019, 3:40 PM
@elizarov Does
suspend fun main
inject/reuse the JVM initial thread into
Dispatchers.Default
? If not, is it possible without major drawbacks?
e

elizarov

08/12/2019, 5:30 PM
The major drawback is that UI apps might also have suspend fun main
d

Dico

08/12/2019, 5:38 PM
@louiscad suspend fun main can't use Dispatchers.Default because that's kotlinx
Although it will default to that dispatcher in kotlinx because context contains no dispatcher
l

louiscad

08/12/2019, 6:36 PM
It'd be nice to have it configurable then.
@Dico I remember reading it checking if kotlinx.coroutines is in the classpath.
d

Dico

08/12/2019, 10:24 PM
I take that back, I'm pretty sure it's single thread event loop
That would be pretty poor design honestly
l

louiscad

08/12/2019, 10:43 PM
I know
suspend fun main
does result in a multi-threaded coroutineContext regardless.