Is there a way to get the parent Job from coroutin...
# coroutines
s
Is there a way to get the parent Job from coroutinecontext's Job without using reflection to get privates?
g
Reflection???
Just use
val parentJob: Job? = coroutineContext[Job]
s
That's not the parent job, that's the existing job
runBlocking { val job1 = this.coroutineContext[Job] launch { val job2 = this.coroutineContext[Job] println(job1 == job2) launch { val job3 = this.coroutineContext[Job] println(job2 == job3) } } }
g
🤔
What is your use case for this?
s
job2 has a reference to job1 internally as it's created with Job(parentJob) but it doesnt seem to expose parentHandle
g
Yes, and it sounds reasonable
s
I want to play with the idea of getting the tree of jobs that lead to a failure by walking Job.parentJob until null for some logging purposes
It might turn out a bad idea, but I'm surprise that Job? parentJob isn't exposed on Job
Able to do it with
Copy code
@UseExperimental(InternalCoroutinesApi::class)
fun Job.getParent() : Job? {
    return (AbstractCoroutine::class.java as Class<*>)?.
        getDeclaredField("parentContext")?.
        also { it.isAccessible = true }?.
        let { it.get(this) as? CoroutineContext? }?.
        let { it[Job] }
}
then get true
Copy code
runBlocking {


            val job1 = this.coroutineContext[Job]

            launch {

                val job2 = this.coroutineContext[Job]
                val parent = job2!!.getParent()
                println(parent == job1)


            }
        }