Hello! Is anyone able to explain why `withContext`...
# coroutines
k
Hello! Is anyone able to explain why
withContext
might be switching coroutine context, but not execution thread in the following example? We’re running into this problem in some code in a work project, but have managed to isolate out all proprietary code. Here’s the failing unit test.
Copy code
@Test fun isolateFailing() = runBlocking(TestCoroutineDispatcher()) {
    val outerThread = Thread.currentThread()
    val singleThreadedContext = newSingleThreadContext("test")
    var innerThread: Thread? = null
    val function = suspend {
      innerThread = withContext(this@runBlocking.coroutineContext) {
        Thread.currentThread()
      }
    }

    val job = launch {
      withContext(singleThreadedContext) {
        function()
      }
    }

    job.join()
    assertThat(outerThread).isEqualTo(innerThread)
  }
The interesting bit is that omitting the
TestCoroutineDispatcher
makes the test pass! I’ve been diving through the internals to try and figure it out with no luck. Does anyone have any insight?