withExecutionContext

withExecutionContext

Signature

Description

Allows running an inner route using an alternative ExecutionContext in place of the default one.

The execution context can be extracted in an inner route using extractExecutionContext directly, or used by directives which internally extract the materializer without sufracing this fact in the API.

Example

val special = system.dispatchers.lookup("special")

def sample() =
  path("sample") {
    extractExecutionContext { implicit executor =>
      complete {
        Future(s"Run on ${executor.##}!") // uses the `executor` ExecutionContext
      }
    }
  }

val route =
  pathPrefix("special") {
    withExecutionContext(special) {
      sample() // `special` execution context will be used
    }
  } ~ sample() // default execution context will be used

// tests:
Get("/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Run on ${system.dispatcher.##}!"
}
Get("/special/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Run on ${special.##}!"
}

Contents