What's the use and meaning of second type parameter in akka.Source

我只是一个虾纸丫 提交于 2019-12-13 00:34:19

问题


What's the use and meaning of second type parameter in akka.Source?

Sample Code:-

  def stream: ServiceCall[Source[String, NotUsed], Source[String, NotUsed]]

According to as much code I have seen up to now by default second type parameter is set to akka.NotUsed. But I don't know what's the significance of it.


回答1:


The second parameter is the materialized value, that is, when you run the source, it's the value that gets returned by the run method to you. All stream shapes in Akka streams have them, that is, sources, sinks, flows, bidiflows, etc. With sinks, it's really obvious, if you're folding the stream, you're going to end up with a single value, that value is given to you through the materialized value, which is a future of the result:

def fold[U, T](zero: U)(f: (U, T) ⇒ U): Sink[T, Future[U]]

For sources though, it's less obvious, but here's one example:

def actorRef[T](bufferSize: Int, overflowStrategy: OverflowStrategy): Source[T, ActorRef]

This is a Source that, when you run it, materializes to an ActorRef. Every message that you send to the actor will be emitted from the source. If you wanted to use this in Lagom, you would do something like this:

def stream = ServiceCall { _ =>
  Source.actorRef[String](16, OverflowStrategy.dropHead)
    .mapMaterializedValue { actor =>
      // send messages here, or maybe pass the actor to somewhere else
      actor ! "Hello world"
      // And return NotUsed so that it now materializes to `NotUsed`, as required by Lagom
      NotUsed
    }
}


来源:https://stackoverflow.com/questions/46499925/whats-the-use-and-meaning-of-second-type-parameter-in-akka-source

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!