is there a coroutines implementation for general J...
# coroutines
r
is there a coroutines implementation for general JVM apps, e.g. a desktop application?
d
Yes but for specific GUI frameworks. JavaFX, Swing, etc.
r
ouch
i am using coroutines for server things... did not expect UI to be involved
d
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
That solved it, thank you! 😄
l
If your app starting point is the
main
function, you can just start it that way:
Copy code
suspend fun main(): Unit = coroutineScope {
    // app starts here, launch coroutines and all
}
d
Might as well just use
runBlocking
, right?
l
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
Reuse appeals to me. Also this can be done.
Copy code
fun main() = runBlocking(Dispatchers.Default) {
    // stuff
}
Although, that doesn't look much better that your initial example. So 🤷🏼 I guess.
l
@elizarov Does
suspend fun main
inject/reuse the JVM initial thread into
Dispatchers.Default
? If not, is it possible without major drawbacks?
e
The major drawback is that UI apps might also have suspend fun main
d
@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
It'd be nice to have it configurable then.
@Dico I remember reading it checking if kotlinx.coroutines is in the classpath.
d
I take that back, I'm pretty sure it's single thread event loop
That would be pretty poor design honestly
l
I know
suspend fun main
does result in a multi-threaded coroutineContext regardless.