How does one close an Akka stream?

旧时模样 提交于 2019-12-11 01:29:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!