Akka Streams:使用KillSwitch关闭后创建另一个RunnableGraph

时间:2016-12-30 09:51:03

标签: scala akka akka-stream

我尝试关闭转换某些数字的流并创建同一图表蓝图的另一个流。但是,第二个流实例不会运行,或者至少它不会向控制台打印任何内容。

我错过了什么?

object KillSwitchSample extends App {
  implicit val actorSystem = ActorSystem()
  implicit val materializer = ActorMaterializer()

  val killSwitch = KillSwitches.shared("switch")

  val stream1 = createStream("stream 1")
  stream1.run()
  Thread.sleep(200)
  killSwitch.shutdown()

  val stream2 = createStream("stream 2")
  stream2.run()
  Thread.sleep(200)
  killSwitch.shutdown()

  def createStream(streamName: String): RunnableGraph[NotUsed] = {
    Source.fromGraph(new NumbersSource)
      .via(killSwitch.flow)
      .map(el => s"$streamName: $el")
      .to(Sink.foreach(println))
  }
}

class NumbersSource extends GraphStage[SourceShape[Int]] {
  val out: Outlet[Int] = Outlet("NumbersSource")
  override val shape: SourceShape[Int] = SourceShape(out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
    new GraphStageLogic(shape) {
      private var counter = 1

      setHandler(out, new OutHandler {
        override def onPull(): Unit = {
          push(out, counter)
          counter += 1
        }
      })
    }
}

1 个答案:

答案 0 :(得分:4)

您使用共享的cell.imgPost.sd_setImage(with: NSURL() as URL!, placeholderImage: UIImage(), options: [], progress: { (_, _) in }, completed: { (_, _, _, _) in }) 。共享KillSwitch只能切换一次,之后它会记住它已被切换,因此也会立即终止终止后续流。

这就是您的代码所发生的事情。您在第二次运行图表之前触发了kill开关。

您可以使用KillSwitch代替每次获得新的KillSwitches.single

KillSwitch