https://kotlinlang.org logo
Title
e

Exerosis

03/30/2022, 1:14 AM
suspend fun debug() {
    println("${coroutineContext[STreeEvent]}")
}
fun main() = runBlocking {
    val test = SSubject(0)
    SComponent().apply {
        println("Component: $this")
        println("Test: $test")
        test(this, BEFORE) {
            println("${coroutineContext[STreeEvent]}")
            debug()
        }
...
Can someone help me understand why :
println("${coroutineContext[STreeEvent]}")
            debug()
prints:
null
1212899836
Why on earth would the context change between these two places?
e

ephemient

03/30/2022, 1:24 AM
probably first one is kotlinx.coroutines.CoroutineScope.coroutineContext (on `runBlocking`'s scope) and second one is kotlin.coroutines.coroutineContext
e

Exerosis

03/30/2022, 1:25 AM
😮 why do they shadow eachother?
r

Richard Gomez

03/30/2022, 2:06 AM
@Exerosis What happens if you change debug to:
- suspend fun debug() {
+ suspend fun debug(): Unit = coroutineScope {
e

ephemient

03/30/2022, 2:10 AM
the problem is the other way around, whatever test is doing, it's not passing its newly created scope to its lambda block
I expect you'd see more consistent results with
coroutineScope {
    println(...)
    debug()
}
r

Richard Gomez

03/30/2022, 2:37 AM
the problem is the other way around,
You're right, I misread that. Long day... 😴
j

Joffrey

03/30/2022, 6:04 AM
It's for this reason that you should avoid
coroutineContext
when you want the one from the current suspend function, use
currentCoroutineContext()
instead in this case
e

Exerosis

03/31/2022, 3:20 AM
When do you even want CoroutineScope.coroutineContext? I'm a little confused
e

ephemient

03/31/2022, 3:22 AM
within low-level machinery code - it is a non-suspending way to extract the context of a CoroutineScope, whereas the built-in mechanism only works in suspending context and is actually implemented by compiler magic
you should not be using either
e

Exerosis

04/05/2022, 3:43 AM
Don't have a huge amount of choice seemingly. But I see the idea now. Thank you!