akka-stream-如何在流/图中不同地对待流的最后一个元素 [英] akka-stream - How to treat the last element of a stream differently in a Flow/Graph
问题描述
我正在尝试实现Akka流Flow
,它将把JSON对象流转换为单个JSON对象数组的流.我可以使用Concat
在元素之间插入逗号,然后在Zip
之前添加"[",但是不能弄清楚如何不插入最后一个逗号.
I'm trying to implement an Akka Streams Flow
that will convert a stream of JSON objects to a stream of a single array of JSON objects. I can use Concat
to add an "[" before and "]" after, as well as Zip
to insert commas in between elements, but I can't figure out how to not insert the final comma.
到目前为止,我的代码是:
The code I have so far is:
trait JsonStreamSupport {
protected def toJsonArrayString[T : Writes] = Flow[T].map(Json.toJson(_)).map(_.toString()).via(jsonArrayWrapper)
private[this] val jsonArrayWrapper: Flow[String, String, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit b =>
import GraphDSL.Implicits._
val start = Source.single("[")
val comma = Source.repeat(",")
val end = Source.single("]")
val concat = b.add(Concat[String](3))
val zip = b.add(Zip[String,String])
comma ~> zip.in1
start ~> concat.in(0)
zip.out.map({case (msg,delim) => msg + delim}) ~> concat.in(1)
end ~> concat.in(2)
FlowShape(zip.in0, concat.out)
})
}
当前输出为:
[{"key":"value},{"key","value"},]
但我需要成为
[{"key":"value},{"key","value"}]
(不带最后一个逗号),
其中数组的每个元素仍然是流的不同元素,因此可以例如分别通过分块HTTP发送.
Currently the output is:
[{"key":"value},{"key","value"},]
but I need it to be
[{"key":"value},{"key","value"}]
(without final comma),
where each element of the array is still a distinct element of the stream so can be, for example, sent over chunked HTTP separately.
推荐答案
刚刚发现了有关intersperse
的信息,这正是您所需要的,并且比我最初建议的要简单得多:
just found out about intersperse
which is exactly what you need, and much simpler than what I suggested in the first place: