https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

sitepodmatt

02/28/2019, 3:36 AM
Is there a way to get the parent Job from coroutinecontext's Job without using reflection to get privates?
g

gildor

02/28/2019, 4:34 AM
Reflection???
Just use
val parentJob: Job? = coroutineContext[Job]
s

sitepodmatt

02/28/2019, 6:55 AM
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

gildor

02/28/2019, 6:57 AM
🤔
What is your use case for this?
s

sitepodmatt

02/28/2019, 6:57 AM
job2 has a reference to job1 internally as it's created with Job(parentJob) but it doesnt seem to expose parentHandle
g

gildor

02/28/2019, 6:57 AM
Yes, and it sounds reasonable
s

sitepodmatt

02/28/2019, 6:58 AM
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)


            }
        }
3 Views