withExecutionContext

withExecutionContext

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 sufracing this fact in the API.

Example

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

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

final Route route = route(
  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() + "!");

Contents