dynamicIf
Enforces that the code constructing the inner route is run for every request if the condition is true.
Signature
def dynamicIf(enabled: Boolean): ByNameDirective0
Description
The effect of dynamicIf(true)
is the same as for dynamic
. The effect of dynamicIf(false)
is the same as
just the nested block.
dynamicIf
is a special directive because, in fact, it doesn’t implement Directive
at all. That means you cannot
use it in combination with the usual directive operators.
Use dynamic
to run the inner route constructor dynamically unconditionally.
Example
def countDynamically(dyn: Boolean) = {
var value = 0
dynamicIf(dyn) {
value += 1 /// executed for each request
complete(s"Result is now $value") // route executed in future
}
}
val route =
path("dynamic")(countDynamically(true)) ~
path("static")(countDynamically(false))
Get("/dynamic") ~> route ~> check {
responseAs[String] === "Result is now 1"
}
Get("/dynamic") ~> route ~> check {
responseAs[String] === "Result is now 2"
}
Get("/dynamic") ~> route ~> check {
responseAs[String] === "Result is now 3"
}
Get("/static") ~> route ~> check {
responseAs[String] === "Result is now 1"
}
Get("/static") ~> route ~> check {
responseAs[String] === "Result is now 1"
}
Get("/static") ~> route ~> check {
responseAs[String] === "Result is now 1"
}