问题
I am updating some experimental spray code to akka-stream (2.0.2), so I'm going through he documentation little by little. One of the needs I have is that if I detect a protocol violation in my stream, I need to close the stream immediately and kick off the client.
What is the proper way of immediately closing (terminating) the stream from inside a Flow?
回答1:
Use a PushStage
:
import akka.stream.stage._
val closeStage = new PushStage[Tpe, Tpe] {
override def onPush(elem: Tpe, ctx: Context[Tpe]) = elem match {
case elem if shouldCloseStream ⇒
// println("stream closed")
ctx.finish()
case elem ⇒
ctx.push(elem)
}
}
You can combine a PushStage
with a Flow
through the transform
method:
Flow[Tpe]
.map(...)
.transform(() ⇒ closeStage)
.map(...)
来源:https://stackoverflow.com/questions/34954144/how-does-one-close-an-akka-stream