我已经和Akka-Streams一起玩了,我试图通过实现自己的Flow
来制作自定义PushPullStage
。我希望Flow
将从上游接收的对象累积到列表中,并在上游完成时向下游发送组之前根据某个函数对它们进行分组。
实施起来似乎很简单,但我无法弄清楚如何做到这一点!似乎不是从PushPullStage
发出多个对象的方法。
到目前为止,这是我的实现:
class Accumulate[A] extends PushPullStage[A, List[A]] {
private var groups: List[List[A]] = Nil
private def group(x: A): List[List[A]] = ...
override def onPush(elem: A, ctx: Context[A]): SyncDirective = {
groups = group(elem)
ctx.pull()
}
override def onPull(ctx: Context[A]): SyncDirective =
if (ctx.isFinishing) {
for(group <- groups)
ctx.push(group) // this doesn't work
ctx.finish()
} else {
ctx.pull()
}
override def onUpstreamFinish(ctx: Context[A]): TerminationDirective =
ctx.absorbTermination()
}
}
修改
我更改了代码以解决压力问题,现在一切正常。基本上我只需要让下游Flow
做他们意想不到的事情并继续拉动元素:
class Accumulate[A] extends PushPullStage[A, List[A]] {
private var groups: List[List[A]] = Nil
private def group(x: A): List[List[A]] = ...
override def onPush(elem: A, ctx: Context[A]): SyncDirective = {
groups = group(elem)
ctx.pull()
}
override def onPull(ctx: Context[A]): SyncDirective =
if (ctx.isFinishing) {
groups match {
case Nil => ctx.finish()
case head :: tail =>
groups = tail
ctx.push(head)
}
} else {
ctx.pull()
}
override def onUpstreamFinish(ctx: Context[A]): TerminationDirective =
ctx.absorbTermination()
}
}