I started to use Play 2.5 recently, and I was wondering what the purpose of doing the following was:
@Inject() (implicit val mat: Materializer)
I had several pieces of code not working and solved that issue thanks to this, but I still don't see what the materializer is doing.
Thanks
Materializing means producing the results of a graph
A materializer makes actors execute a graph to produce those results.
A graph, in its simplest form, consists of a source that provides elements, and a sink that consumes elements.
Here's a source that provides a range of integers (in this example, integers are our elements):
And here's a sink that sums all the integers it gets from a source:
We connect source and sink to get a graph:
Mind that no computation, addition in our case, is performed when creating a graph. The code is declarative, the graphs describe how we want to transform our data but it is someone else's job to actually perform the computation: Graphs are blueprints.
Now, what about the materializer? The materializer takes action when we run the graph:
When we
run()
the graph, the materializer takes the graph and makes actors execute the data transformations specified in the graph; in this example, that's adding integers.It might be helpful to imagine the graph as a blueprint to build a house, the materializer as the foreman looking at the blueprint, telling the builders how to actually build the house according to the blueprint. The builders in this analogy correspond to actors in Akka.
The reason why several pieces of your code now work, is that with the materializer you provide a way to execute graphs. Graphs are heavily used in Akka HTTP which Play uses for HTTP requests and responses.
The WSClient you mentioned in your comment uses graphs to perform its requests and thus needs a materializer.
Here's a full example of creating and running a graph:
Put this in your
build.sbt
to make Akka's stream library available in your code:Here's more on sources and sinks.