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
sourcedef 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
sourceimport static org.apache.pekko.http.javadsl.server.Directives.extractExecutionContext;

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() + "!");