如何停止Actor中的Source.tick?

时间:2019-05-11 18:35:01

标签: scala akka akka-stream

我有一个演员,每2秒产生一次NotUsed。也许这没有任何意义,但仅用于测试目的。

import akka.NotUsed
import akka.actor.{Actor, ActorLogging, Props}
import akka.stream.{ActorMaterializer, KillSwitches}
import akka.stream.scaladsl.{Keep, Sink, Source}
import com.sweetsoft.FsmSystem.{Add, StartTicker, StopTicker}

import scala.concurrent.duration._

object AddActor {

  def props: Props = Props(new AddActor)

}

final class AddActor extends Actor with ActorLogging {

  implicit val materilizer = ActorMaterializer()

  private val consumer: NotUsed => Unit = _ =>
    context.parent ! Add

  private val runnable = Source.tick(2.second, 2.second, NotUsed)
    .named("Ticker")
    .toMat(Sink.foreach(consumer))(Keep.both)

  override def receive: Receive = {
    case StartTicker =>

      runnable.run()
    case StopTicker =>

  }
}  

Actor收到消息StopTicker时,我想停止流。然后通过StartTicker,启动流。

调用run()方法,我将获得物化值Cancellabel,但是在StopTicker范围内无法访问。

我该怎么办?

1 个答案:

答案 0 :(得分:4)

您可以使用becode/unbecome模式:

final class AddActor extends Actor with ActorLogging {
    import context._

    implicit val materilizer: ActorMaterializer = ActorMaterializer()

    private val consumer: NotUsed => Unit = _ =>
      self ! Add //send Add to self rather than directly to context.parent

    private val runnable = Source.tick(2.second, 2.second, NotUsed)
      .named("Ticker")
      .toMat(Sink.foreach(consumer))(Keep.both)

    override def preStart(): Unit = { //start runnable on actor start
      super.preStart()
      runnable.run()
    }

    val running: Receive = { //when running ignore new StartTicker but handle StopTicker and Add
      case StopTicker =>
        become(paused)

      case Add =>
        context.parent ! Add
    }

    val paused: Receive = { //handle just StartTicker
      case StartTicker =>
        become(running)
    }

    override def receive: Receive = paused //initial receive is paused

}