Understanding how to start coroutines

So I understand Kotlin has various Coroutine Dispatchers which create and launch coroutines. Examples: launch, async, runBlocking, etc.

So far, to the best of my knowledge you can only create/run a coroutine inside of a coroutine, or in a runBlocking{} dispatcher in the main method. How else can a coroutine be called? Are these the only options available? It seems like runBlocking is the main entry point for all coroutines but this seems wrong to me.

1 Like

These are coroutine builders (not to confuse with dispatchers).

In the end coroutine builders start the provided suspend functions with the startCoroutine extension function located in the standard library.

runBlocking is not the only entry point for coroutines. Conversely, any coroutine builder is an entry point to the coroutine suspend world, but runBlocking could be useful to bridge back to the blocking world.

Also you can do without runBlocking as well, if you start your program directly as a coroutine. That’s what suspend fun main() { } is for. Inside that main function you can readily invoke other suspend functions.

1 Like

If I were to use launch or async in main without declaring a scope, the compiler would complain. Would they have to be GlobalScope, or could I create my own scope?

Yes. Either way works.

GlobalScope and runBlocking are to be avoided so it has been said. So, either is not really a good way forward right?

You should generally not use GlobalScope so you can take advantage of structured concurrency, but there can be times when you want a coroutine to have the same lifecycle as the entire app. GlobalScope can be used in that case.

1 Like