withExecutionContext

Signature

def withExecutionContext(ec: ExecutionContextExecutor): Directive0 

Description

Allows running an inner route using an alternative ExecutionContextExecutor 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 surfacing this fact in the API.

Example

Scala
sourceval 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.##}!"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.withExecutionContext;


final ExecutionContextExecutor special =
    ExecutionContexts.fromExecutor(Executors.newFixedThreadPool(1));

final Route sample =
    path(
        "sample",
        () ->
            extractExecutionContext(
                executor ->
                    onSuccess(
                        () ->
                            CompletableFuture.supplyAsync(
                                () -> "Run on " + executor.hashCode() + "!", executor),
                        Directives::complete)));

final Route route =
    Directives.concat(
        pathPrefix(
            "special",
            () ->
                // `special` execution context will be used
                withExecutionContext(special, () -> sample)),
        sample // default execution context will be used
        );

// tests:
testRoute(route)
    .run(HttpRequest.GET("/sample"))
    .assertEntity("Run on " + system().dispatcher().hashCode() + "!");
testRoute(route)
    .run(HttpRequest.GET("/special/sample"))
    .assertEntity("Run on " + special.hashCode() + "!");