extractExecutionContext

Signature

def extractExecutionContext: Directive1[ExecutionContextExecutor]

Description

Extracts the ExecutionContext from the RequestContextRequestContext.

See withExecutionContext to see how to customise the execution context provided for an inner route.

See extract to learn more about how extractions work.

Example

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

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

// tests:
Get("/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Run on ${system.dispatcher.##}!"
}
Java
final Route route = path("sample", () ->
  extractExecutionContext(executor ->
    onSuccess(
      CompletableFuture.supplyAsync(
        // uses the `executor` ExecutionContext
        () -> "Run on " + executor.hashCode() + "!", executor
      ), str -> complete(str)
    )
  )
);

// tests:
testRoute(route).run(HttpRequest.GET("/sample"))
  .assertEntity("Run on " + system().dispatcher().hashCode() + "!");
The source code for this page can be found here.