Skip to content

Coroutine context lost easily between calls #4499

@whirvis

Description

@whirvis

Describe the bug

When passing a Job as a CoroutineContext, the rest of the context is lost. I have a code fragment which produces unexpected output. When running it, I expect the following output:

CoroutineName(foo)
    CoroutineName(bar)
    CoroutineName(baz)
    CoroutineName(qux)
579

But instead, I get this:

CoroutineName(foo)
    DeferredCoroutine{Active}@2bea5ab4
    DeferredCoroutine{Active}@3d8314f0
    DeferredCoroutine{Active}@2df32bf7
579

After some digging, I realized this is because CoroutineContext.Element (implemented by Job) also implements CoroutineContext. In the implementation for CoroutineContext.Element, we find the following:

public override operator fun <E : Element> get(key: Key<E>): E? =
       @Suppress("UNCHECKED_CAST")
       if (this.key == key) this as E else null

Personally, I find this behavior very confusing and unexpected. Is there a reason why CoroutineContext.Element implements the CoroutineContext interface? (also: if the code fragment I gave is not optimal, please state so. I am new to Kotlin coroutines and I want to use them correctly.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions