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

Viktor Qvarfordt

05/16/2019, 10:24 PM
What does it mean to declare main as
suspend
, ie.
suspend fun main() { ... }
? Is it equivalent to having
fun main() = runBlocking { ... }
or something else?
g

gildor

05/16/2019, 10:26 PM
Not exactly, runBlocking also creates CoroutinesScope, so you can use launch/async/etc coroutines builders
Main point about suspend main, that it's part of the language, but runBlocking is library function of kotlinx.coroutines
v

Viktor Qvarfordt

05/16/2019, 10:27 PM
Right, didn’t think about coroutine builders. My main was just calling other suspend functions
e

elizarov

05/16/2019, 10:39 PM
runBlocking
also confined your coroutines to the main thread (install its own distacher), but the code in
suspend main
executes in a default dispatcher. Only really matters when yo go
coroutineScope { ... }
and start launching coroutines from there.
s

simon.vergauwen

05/16/2019, 10:58 PM
Is there a reason for this difference?
l

louiscad

05/17/2019, 12:06 AM
@simon.vergauwen Yes.
runBlocking
is not the default dispatcher at all, but uses the (single) thread it blocks as the dispatcher. Very different from using
suspend fun main()
and letting it use the default dispatcher (quite correctly named
Dispatchers.Default
).
s

simon.vergauwen

05/17/2019, 12:12 AM
Thanks. Why doesn't
suspend fun main()
start on main?
e

elizarov

05/17/2019, 5:22 AM
For simplicity. It is built into the language, as opposed high-level library function like
runBlocking
👍 1
2 Views