简体   繁体   中英

Akka-streams - how to access the materialized value of the stream

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM