withMaterializer

Signature

def withMaterializer(materializer: Materializer): Directive0

Description

Allows running an inner route using an alternative MaterializerMaterializer in place of the default one.

The materializer can be extracted in an inner route using extractMaterializer directly, or used by directives which internally extract the materializer without surfacing this fact in the API (e.g. responding with a Chunked entity).

Example

Scala
sourceval special = Materializer(system).withNamePrefix("special")

def sample() =
  path("sample") {
    extractMaterializer { mat =>
      complete {
        // explicitly use the materializer:
        Source.single(s"Materialized by ${mat.##}!")
          .runWith(Sink.head)(mat)
      }
    }
  }

val route =
  pathPrefix("special") {
    withMaterializer(special) {
      sample() // `special` materializer will be used
    }
  } ~ sample() // default materializer will be used

// tests:
Get("/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Materialized by ${SystemMaterializer(system).materializer.##}!"
}
Get("/special/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Materialized by ${special.##}!"
}
Java
sourceimport static akka.http.javadsl.server.Directives.withMaterializer;

final ActorMaterializerSettings settings = ActorMaterializerSettings.create(system());
final Materializer special = akka.stream.ActorMaterializer.create(settings, system(), "special");

final Route sample = path("sample", () ->
  extractMaterializer(mat ->
    onSuccess(() ->
      // explicitly use the materializer:
      Source.single("Materialized by " + mat.hashCode() + "!")
        .runWith(Sink.head(), mat), Directives::complete
    )
  )
);

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

// tests:
testRoute(route).run(HttpRequest.GET("/sample"))
  .assertEntity("Materialized by " + materializer().hashCode()+ "!");
testRoute(route).run(HttpRequest.GET("/special/sample"))
  .assertEntity("Materialized by " + special.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.