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
import static akka.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() + "!");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.