Easy way to access coroutine context from nested suspending functions


#1

Hi,

Is there a way to access the coroutine context (without explicitly passing it) from a suspending function and calling other suspendig functions without creating a new coroutine in the process?

Here is some sample code what I try to accomplish, but the exposeContext function has to start a new coroutine so that the lambda could call other suspending functions:

fun start(){
    // put something into initial context
    kotlinx.coroutines.experimental.run(CommonPool) {
        // cal a suspend method
        a()
    }
}


suspend fun a() {
    // call other suspending function
    b()
}

suspend fun b() = exposeContext {

    //Access the context, do something with it
    val ctx = it

    // call other suspending function
    c()
}

suspend fun c(){

}


suspend fun <T : Any> exposeContext(block: suspend (CoroutineContext) -> T) = suspendCoroutine<T> {

    launch(context = it.context) {
        try {
            it.resume(block(it.context))
        } catch (e: Exception) {
            it.resumeWithException(e)
        }
    }
}

#2

It is planned. It will be called coroutineContext. See https://youtrack.jetbrains.com/issue/KT-17609