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

JP

03/20/2020, 12:16 PM
Copy code
fun main() = runBlocking { // this: CoroutineScope

    coroutineScope { // Creates a coroutine scope
        println(this)
        println(this@runBlocking)
...
and the printed result is:
Copy code
"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?
f

Francisco Javier Ruiz Rodriguez

03/20/2020, 12:20 PM
I think
coroutine#1
is the parent of both, in this case, thew
runBlocking
Try this, and you will see the difference:
Copy code
import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    coroutineScope { // Creates a coroutine scope
        println(this)
        println(this@runBlocking)
        test()
    }
}

fun test() = runBlocking {
    println(this)
}
e

elizarov

03/20/2020, 12:22 PM
coroutineScope { ... }
does not create a new coroutine, even though it has its own
Job
instance, and thus also uses the same id.
🙂 3
j

JP

03/20/2020, 12:27 PM
I see, I just vaguely thought after simply skimming through the
coroutineScope
function
Copy code
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.
e

elizarov

03/20/2020, 1:00 PM
The trick is how you define a "coroutine". Here we use a narrower definition, where a "coroutines" is something that works concurrently with the rest of your code. Since
coroutineScope { ... }
(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.
👍 1
8 Views