JP
03/20/2020, 12:16 PMfun main() = runBlocking { // this: CoroutineScope
coroutineScope { // Creates a coroutine scope
println(this)
println(this@runBlocking)
...
and the printed result is:
"coroutine#1":ScopeCoroutine{Active}@64a294a6
"coroutine#1":BlockingCoroutine{Active}@7e0b37bc
Why do they have the same name “coroutine#1”?
If they are different coroutines, shouldn’t they have different labels?
Am I missing something?Francisco Javier Ruiz Rodriguez
03/20/2020, 12:20 PMcoroutine#1
is the parent of both, in this case, thew runBlocking
Try this, and you will see the difference:
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
coroutineScope { // Creates a coroutine scope
println(this)
println(this@runBlocking)
test()
}
}
fun test() = runBlocking {
println(this)
}
elizarov
03/20/2020, 12:22 PMcoroutineScope { ... }
does not create a new coroutine, even though it has its own Job
instance, and thus also uses the same id.JP
03/20/2020, 12:27 PMcoroutineScope
function
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R =
suspendCoroutineUninterceptedOrReturn { uCont ->
val coroutine = ScopeCoroutine(uCont.context, uCont)
coroutine.startUndispatchedOrReturn(coroutine, block)
}
that it would create a new coroutine. Then I guess here val coroutine = ScopeCoroutine(uCont.context, uCont)
does not return a new coroutine.elizarov
03/20/2020, 1:00 PMcoroutineScope { ... }
(unline launch
) is not concurrent with the surrounding code we don't call it a "coroutine builder" and we don't consider it to actually create a new coroutine.