Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

withContext calls ThreadContextElement#updateThreadContext with wrong Job in context #3411

Closed
dovchinnikov opened this issue Aug 17, 2022 · 0 comments
Labels

Comments

@dovchinnikov
Copy link
Contributor

import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.job
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.ThreadContextElement

class MyElement : ThreadContextElement<Unit> {

  companion object Key : CoroutineContext.Key<MyElement>

  override val key: CoroutineContext.Key<*> get() = Key

  override fun updateThreadContext(context: CoroutineContext) {
    println("update ${context.job}") // both times BlockingCoroutine{Active}@18ef96 
  }

  override fun restoreThreadContext(context: CoroutineContext, oldState: Unit) {}
}

fun main() {
  runBlocking(MyElement()) {
    println("outer ${coroutineContext.job}") // BlockingCoroutine{Active}@18ef96
    withContext(MyElement()) {
        println("inner ${coroutineContext.job}") // UndispatchedCoroutine{Active}@2aaf7cc2
    }
  }
}

This happens because withContext calls withCoroutineContext with newContext which doesn't include newly created UndispatchedCoroutine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants