我想了解akka流中toMat的作用。例如:
val sink1:Sink[Int, Future[Int]]=Sink.fold[Int,Int](0)(_ + _)
val flow=Flow[Int].fold[Int](0){(x,y)=> x+y}
val runnable = Source (1 to 10).viaMat(flow)(Keep.right).toMat(sink1)(Keep.both)
谢谢
阿伦
最佳答案
override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = viaMat(flow)(Keep.left)
(a:A,b:B) => (a, b)
的别名,该函数接受两个输入参数并将它们作为元组返回。合并两个流(或源和流或流和接收器等)时,它通常具有左侧和右侧的物化值。我将剖析您的代码行:
// you're keeping the materialized value of flow
val source2 = Source (1 to 10).viaMat(flow)(Keep.right)
// you're keeping both materialized values, i.e. the one of flow from previous step
// and the one o sink.
val runnableGraph = source2.toMat(sink)(Keep.both)
runnableGraph.run() // returns a tuple (flowMatVal, sinkMatVal)
当您将流的两个部分(即源和流/接收器或流和接收器)连接在一起时,每个部分都具有您在运行流时获得的物化值。与via / to组合时的默认行为是保留左侧。如果使用viaMat / toMat,则可以选择保留正确的物化值或将两者都保留为元组。