How to get the CoroutineContext of a Job

Dec 27, 2021

Getting the CoroutineContext a coroutine runs in by just having a Job instance is harder than I thought. A Job more or less represents a running coroutine, so it shouldn’t be that hard, right? Here’s is the solution I got working:

val Job.coroutineContext: CoroutineContext
    get() = (this as CoroutineScope).coroutineContext

/**
 * Please include this test in your code-base `Job.coroutineContext` uses
 * unofficial API that might stop working in future coroutine versions.
 * This test class will detect it.
 * If this test starts failing, check back on:
 * https://xa1.at/kotlin-coroutine-job-context/
 */
class JobCoroutineContextTest {

    @Test
    fun `returns coroutineContext of Job`() = runTest {
        val job = launch(CoroutineName("JobCoroutineContextTest1")) { delay(1) }

        assertEquals("JobCoroutineContextTest1", job.coroutineContext[CoroutineName]!!.name)
    }
}

(This code uses Kotlin 1.6 and kotlinx.coroutines 1.6)

How does it work?

Job doesn’t provide direct access to the CoroutineContext of the coroutine it runs. However, fortunately, the Jobs returned by launch {…} are StandaloneCoroutine instances, which implement AbstractCoroutine, which implements CoroutineScope. If this implementation detail changes, or the Job implementation in use doesn’t implement CoroutineScope, this little hack won’t work.

If you find a better solution, please let me know.

You might also like