如何突然停止 akka 流 Runnable Graph?

Pai*_*nts 5 io scala akka akka-stream scala-streams

我不知道如何立即停止 akka 流 Runnable Graph?如何使用killswitch来实现这一点?我开始使用 akka 流才几天。就我而言,我正在从文件中读取行并在流程中执行一些操作并写入接收器。我想要做的是,只要我想立即停止读取文件,我希望这可能会停止整个运行图。对此的任何想法将不胜感激。

提前致谢。

lpi*_*ora 2

从 Akka Streams 2.4.3 开始,有一种优雅的方法可以通过 来从外部停止流KillSwitch

考虑以下示例,该示例在 10 秒后停止流。

object ExampleStopStream extends App {

  implicit val system = ActorSystem("streams")
  implicit val materializer = ActorMaterializer()

  import system.dispatcher

  val source = Source.
    fromIterator(() => Iterator.continually(Random.nextInt(100))).
    delay(500.millis, DelayOverflowStrategy.dropHead)
  val square = Flow[Int].map(x => x * x)
  val sink = Sink.foreach(println)

  val (killSwitch, done) =
    source.via(square).
    viaMat(KillSwitches.single)(Keep.right).
    toMat(sink)(Keep.both).run()

  system.scheduler.scheduleOnce(10.seconds) {
    println("Shutting down...")
    killSwitch.shutdown()
  }

  done.foreach { _ =>
    println("I'm done")
    Await.result(system.terminate(), 1.seconds)
  }

}
Run Code Online (Sandbox Code Playgroud)