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

Elisabet Svensson Duranovic

11/21/2018, 12:22 PM
Hello! We have just upgraded kotlin and coroutines for our service. One thing noted was that main can now be a suspend method. What happens if main gets suspended? Is there any considerations when having long-lived applications? (previously we did a runBlocking { application.start() }, now we just do application.start())
m

marstran

11/21/2018, 12:31 PM
I'm pretty sure
suspend fun main() { ... }
is equivalent to
fun main() = runBlocking { ... }
.
e

Elisabet Svensson Duranovic

11/21/2018, 12:32 PM
thanks! how sure is pretty sure?
m

marstran

11/21/2018, 12:33 PM
I think I've read it somewhere. Trying to find it in the docs now 🙂
e

Elisabet Svensson Duranovic

11/21/2018, 12:42 PM
awesome! thank you!
Do I need to explicitly add the coroutineScope? In the example we have "suspend fun main() = coroutineScope { ... }" and I would have expected just "suspend fun main() { ... }"
m

marstran

11/21/2018, 12:50 PM
You need that if you want to start other coroutines within
main
. Like the `async`s in that example.
So yeah, that is a difference.
runBlocking
would create that scope for you.
e

Elisabet Svensson Duranovic

11/21/2018, 12:58 PM
I'm not sure I follow tbh. When would I/wouldn't I want that? What is the effect of either?
m

marstran

11/21/2018, 1:00 PM
You need a
coroutineScope
to start coroutines like
async
,
launch
,
produce
and so on. It's part of something called "structured concurrency". You can read more about it here: https://medium.com/@elizarov/structured-concurrency-722d765aa952
e

Elisabet Svensson Duranovic

11/21/2018, 1:18 PM
ahh - of course. async and the others start new coroutines - I was confused with just calling other suspend functions. Thanks for the link, will give it a read!
m

marstran

11/21/2018, 1:30 PM
Right. You don't need a scope if you just want to call other suspend functions.
4 Views