Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin Ktor拦截器中的状态_Kotlin_Ktor - Fatal编程技术网

Kotlin Ktor拦截器中的状态

Kotlin Ktor拦截器中的状态,kotlin,ktor,Kotlin,Ktor,我在此帮助页面上遵循以下说明: 他们举了一个例子: fun Route.routeTimeout(time: Long, unit: TimeUnit = TimeUnit.SECONDS, callback: Route.() -> Unit): Route { // With createChild, we create a child node for this received Route val routeWithTimeout = this.createCh

我在此帮助页面上遵循以下说明:

他们举了一个例子:

fun Route.routeTimeout(time: Long, unit: TimeUnit = TimeUnit.SECONDS, callback: Route.() -> Unit): Route {
    // With createChild, we create a child node for this received Route  
    val routeWithTimeout = this.createChild(object : RouteSelector(1.0) {
        override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
            RouteSelectorEvaluation.Constant
    })

    // Intercepts calls from this route at the features step
    routeWithTimeout.intercept(ApplicationCallPipeline.Features) {
        withTimeout(time, unit) {
            proceed() // With proceed we can define code to be executed before and after the call
        }
    }

    // Configure this route with the block provided by the user
    callback(routeWithTimeout)

    return routeWithTimeout
}

我想修改它,以便它可以保持状态。例如,每个下一个调用方都会获得更大的超时。我应该把我的状态放在哪里?

你可以将状态保存在周围的闭包中。我通过增加超时扩展了您的示例:

fun Route.routeTimeout(time: Long, unit: TimeUnit = TimeUnit.SECONDS, callback: Route.() -> Unit): Route {
    // With createChild, we create a child node for this received Route
    val routeWithTimeout = this.createChild(object : RouteSelector(1.0) {
        override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
            RouteSelectorEvaluation.Constant
    })

    // state
    var newTime = time

    // Intercepts calls from this route at the features step
    routeWithTimeout.intercept(ApplicationCallPipeline.Features) {
        try{
            withTimeout(newTime, unit) {
                proceed() // With proceed we can define code to be executed before and after the call
            }
        } catch (e: TimeoutCancellationException) {
            // change the state
            newTime*=2
            throw e
        }
    }

    // Configure this route with the block provided by the user
    callback(routeWithTimeout)

    return routeWithTimeout
}