What does it mean to declare main as `suspend`, ie...
# coroutines
v
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
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
Right, didn’t think about coroutine builders. My main was just calling other suspend functions
e
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
Is there a reason for this difference?
l
@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
Thanks. Why doesn't
suspend fun main()
start on main?
e
For simplicity. It is built into the language, as opposed high-level library function like
runBlocking
đź‘Ť 1