Understanding how to start coroutines

#1

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.

#2

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
#3

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?

#4

Yes. Either way works.