如下代码:

class HotSwapActor extends Actor {
  import context._
  def angry: PartialFunction[Any, Unit] = {
    case "foo" => sender ! "I am already angry!"
    case "bar" => become(happy)
  }

  def happy: PartialFunction[Any, Unit] = {
    case "bar" => sender ! "I am already happy :-)"; unbecome
    case "foo" => become(angry)
  }

  def receive = {
    case "foo" => become(angry)
    case "bar" => become(happy)
  }
}

class OtherActor extends Actor {
  val system = ActorSystem()
  val actor = system.actorOf(Props[HotSwapActor])
  def receive = {
    case "start" =>
      actor ! "foo"
      actor ! "bar"
      actor ! "bar"
      actor ! "foo"
    case a @ _ => println(a)
  }
}

object HotSwapMain extends App {
  val system = ActorSystem()
  val actor = system.actorOf(Props[OtherActor])
  actor ! "start"
}

具有输出:



但是不是吗



还是我在快乐的PartialFunction的情况下缺少中不成为的语义?

最佳答案

这是怎么回事。

  • 消息“foo”已发送-> receive接收消息。 angry成为接收函数。下一封邮件将发送到angry
  • 消息“栏”已发送-> angry接收消息。 happy成为接收函数。下一封邮件将发送到happy
  • 消息“栏”已发送-> happy接收消息。它回复了I am already happy :-)消息。然后是unbecomes
    按照api的所有以前对context.become的所有调用,discardOld默认设置为true。现在,更换自身后,没有任何东西可以成为下一个接收器了。它采用默认的一个即receive作为接收者
  • 消息“foo”已发送-> receive接收消息。 angry成为接收函数。下一封邮件将发送到angry
  • 09-11 19:20