如下代码:
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的栏情况下缺少中不成为的语义?
最佳答案
这是怎么回事。
receive
接收消息。 angry
成为接收函数。下一封邮件将发送到angry
angry
接收消息。 happy
成为接收函数。下一封邮件将发送到happy
happy
接收消息。它回复了I am already happy :-)
消息。然后是unbecomes
。按照api的所有以前对
context.become
的所有调用,discardOld
默认设置为true。现在,更换自身后,没有任何东西可以成为下一个接收器了。它采用默认的一个即receive
作为接收者receive
接收消息。 angry
成为接收函数。下一封邮件将发送到angry