监控akka流的生命周期

时间:2017-08-02 14:59:00

标签: scala akka akka-stream

我想要监视akka-stream的生命周期,似乎monitor会做我需要的,但我的监视功能是异步的,返回Future,所以我需要监视器同样是异步。

monitor具有以下签名:

def monitor[Mat2]()(combine: (Mat, FlowMonitor[Out]) ⇒ Mat2): ReprMat[Out, Mat2]

但我需要类似的东西:

def monitorAsync[Mat2]()(combine: (Mat, FlowMonitor[Out]) ⇒ Future[Mat2]): ReprMat[Out, Mat2]

有没有办法使用像mapAsync这样的akka​​-streams原语实现这一点。

我想我可以使用mapAsync + watchTermination,但当monitor几乎完成我需要的工作时,它似乎是一个复杂的解决方案。

1 个答案:

答案 0 :(得分:0)

原来monitor根本不是我想要的,因为只有在实现流后才能访问FlowMonitor

我最终使用mapAsyncrecover实现了此功能。我在这里简化,但是这样的事情:

val monitor = new Monitor {
  def onNext: Future[Unit] = ???
  def onFailure(cause: Throwable): Future[Unit] = ???
  def onFinish: Future[Unit] = ???
}

source.mapAsync { v => 
  monitor.onNext.map(_ => v)
}.watchTermination() { (mat, doneF) =>
  doneF.flatMap(_ => monitor.onFinish).recoverWith( case ex => monitor.onFailure(ex))
}
相关问题