我正在尝试使用flatMapConcat如下:
Source.empty
.flatMapConcat {
Source.fromFuture(Future("hello"))
}
.runWith(Sink.foreach(println))
.onComplete {
case Success(_) =>
println()
case Failure(e) =>
println(s"Thrown ${e.getMessage}")
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
Error:(31, 26) type mismatch;
found : akka.stream.scaladsl.Source[String,akka.NotUsed]
required: ? => akka.stream.Graph[akka.stream.SourceShape[?],?]
Source.fromFuture(Future("hello"))
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
方法flatMapConcat具有以下签名:
def flatMapConcat[T, M](f: (Out) => Graph[SourceShape[T], M]): Repr[T]
Run Code Online (Sandbox Code Playgroud)
在处理 a Sourceof Strings的情况下,它会期望一个函数,如:
f: String => Source(Iterable[String])
Run Code Online (Sandbox Code Playgroud)
您的示例代码的另一个问题是Source.empty[T]没有要处理的元素,因此flatMapConcat永远不会执行后续操作。
下面是一个使用名称flatMapConcat从 a 转换每个元素的示例Source:
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
implicit val system = ActorSystem("system")
implicit val materializer = ActorMaterializer()
Source(List("alice", "bob", "jenn")).
flatMapConcat{ name => Source(List(s"Hi $name", s"Bye $name")) }.
runWith(Sink.foreach(println))
// Hi alice
// Bye alice
// Hi bob
// Bye bob
// Hi jenn
// Bye jenn
Run Code Online (Sandbox Code Playgroud)
作为旁注,可以flatMapConcat用mapConcat替换上面的示例,它需要一个更简单的函数签名:
Source(List("alice", "bob", "jenn")).
mapConcat{ name => List(s"Hi $name", s"Bye $name") }.
runWith(Sink.foreach(println))
Run Code Online (Sandbox Code Playgroud)