Kotlin 修改ktor调用共同例程上下文

Kotlin 修改ktor调用共同例程上下文,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,因此,我正在使用ktor,希望通过ThreadLocal在整个上下文中提供一些数据。我看到的是: val dataThreadLocal = ThreadLocal<String>() suspend fun fromOtherFunction() = "From other function -- ${dataThreadLocal.get()}" routing { get("/hello") { // [1] launch(this.c

因此,我正在使用
ktor
,希望通过
ThreadLocal
在整个上下文中提供一些数据。我看到的是:

val dataThreadLocal = ThreadLocal<String>()
suspend fun fromOtherFunction() = "From other function -- ${dataThreadLocal.get()}"

routing {
    get("/hello") {
        // [1]
        launch(this.coroutineContext + dataThreadLocal.asContextElement(value = "world")) {
            val fromHere = async {
                "ThreadLocal value: ${dataThreadLocal.get()}"
            }

            val fromThere = async {
                fromOtherFunction()
            }

            call.respond(fromHere.await() + "," + fromThere.await())
        }

    }
}
这显然不起作用,因为
拦截
中的协同路由范围不包含路由的协同路由范围

我相信在幕后发生的是,每个调用都是在父共同例程范围内启动的(类似于我们的“请求线程”)。我有没有办法修改这个上下文?有没有一种方法可以让我在启动新的协同例程上下文时告诉
ApplicationEngine
+
一个额外的上下文元素

intercept(ApplicationCallPipeline.Features) {
    launch(this.coroutineContext + dataThreadLocal.asContextElement(value = "world")) {
    ...
    }
}

routing {
    get("/hello") {
        val threadLocalValue = dataThreadLocal.get()
    ...