How to launch a Kotlin coroutine in a `suspend fun` that uses the current parent Scope?
You should make the function go
an extension function of CoroutineScope
:
fun main() = runBlocking {
go()
go()
go()
println("End")
}
fun CoroutineScope.go() = launch {
println("go!")
}
Read this article to understand why it is not a good idea to start in a suspend
functions other coroutines without creating a new coroutineScope{}
.
The convention is: In a suspend
functions call other suspend
functions and create a new CoroutineScope
, if you need to start parallel coroutines. The result is, that the coroutine will only return, when all newly started coroutines have finished (structured concurrency).
On the other side, if you need to start new coroutines without knowing the scope, You create an extensions function of CoroutineScope
, which itself it not suspendable
. Now the caller can decide which scope should be used.