9

I am learning to work with Akka streams, and really loving it, but the materialization part is still somewhat a mystery to me.

Quoting from http://doc.akka.io/docs/akka-stream-and-http-experimental/snapshot/scala/http/client-side/host-level.html#host-level-api

... trigger the immediate shutdown of a specific pool by calling shutdown() on the HostConnectionPool instance that the pool client flow materializes into

How do I get hold of the HostConnectionPool instance?

Even more importantly, I'd like to understand in general how to access the materialized value and perform some operation or retrieve information from it.

Thanks in advance for any documentation pointers or explanation.

Yardena
  • 2,837
  • 20
  • 17
  • This could be a solution to your question: http://stackoverflow.com/a/36467193/1274237 It's based on the discussion here: https://github.com/akka/akka/issues/17769#issuecomment-206532674 – ncreep Nov 27 '16 at 09:54

1 Answers1

10

This is accomplished with the Source.viaMat function. Extending the code example from the link provided in your question:

import akka.http.scaladsl.Http.HostConnectionPool
import akka.stream.scaladsl.Keep
import akka.stream.scaladsl.RunnableGraph

val poolClientFlow = Http().cachedHostConnectionPool[Int]("akka.io")

val graph: RunnableGraph[(HostConnectionPool, Future[(Try[HttpResponse], Int)])]  =
  Source.single(HttpRequest(uri = "/") -> 42)
        .viaMat(poolClientFlow)(Keep.right)
        .toMat(Sink.head)(Keep.both)

val (pool, fut) = graph.run()

pool.shutdown()

Since Source.single materializes into Unit the Keep.right says to keep the HostConnectionPool which the poolClientFlow materializes into. In the .toMat function the Keep.both says to keep both the left pool from the flow and the right Future from the Sink.

Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125
  • 1
    Thanks a lot for the answer, toMat()(Keep.both) is definitely helpful. However what if I want to access the pool not at the same place in code where I am running the flow? Does it make sense to do something like: Source.empty.viaMat(poolClientFlow)(Keep.right).to(Sink.ignore).run() just to get access to the pool? I guess that in general case each flow can be materialized to a different instance, but here, it's the same shared pool... – Yardena Jan 24 '16 at 19:44
  • @Yardena You are welcome. I have never tried to access the materialized pool outside of the context of a stream. To do that it looks like you can simply call the HostConnectionPool constructor with the same settings as the Http.newHostConnectionPool settings. This should return the same instance, but I wouldn't want to put that in my answer as I have never tried it before. Happy hacking. – Ramón J Romero y Vigil Jan 24 '16 at 19:55
  • Thanks again, I think I will stick with Http().shutdownAllConnectionPools() – Yardena Jan 25 '16 at 08:54