context.become改变阿卡演员的
问题描述:
我正在学习如何使用context.become来控制我的演员状态的行为,我使用这个代码:context.become改变阿卡演员的
class MyActor extends Actor {
override def receive: Receive = {
println("Happens here")
active(Set.empty)
}
def active(isInSet: Set[String]): Receive = {
case Add(key) =>
context.become(active(isInSet+key))
case Contains(key) =>
sender() ! isInSet(key)
case ShowAll =>
println(isInSet.toSeq)
}
}
case class Add(key: String)
case class Contains(key: String)
object ShowAll
object DemoBecome extends App{
override def main(args: Array[String]): Unit = {
val system = ActorSystem("BecomeUnbecome")
val act = system.actorOf(Props(classOf[MyActor]), "demoActor")
act ! Add("1")
act ! ShowAll
act ! Add("2")
act ! ShowAll
Thread.sleep(10000)
System.exit(0)
}
当我发送的第一条消息,在“接收”的作品和打印消息,之后的第二信息不显示,这是我的输出:
Happens here
Set()
Vector(1)
Set(1)
Vector(1, 2)
如果我更改接收方法,对于这个:
def receive = {
case a: Add => println("happens here Add")
case c: Contains => println("happens here Contains")
case ShowAll => println("happens here Show")
}
我收到此输出:
happens here Add
happens here Show
happens here Add
happens here Show
所以我想,跟踪时刻“收到”被“封杀”,但我没有成功,我的疑问是:当我使用context.become在我的演员,阿卡如何以及何时在第一个之后处理消息?
答
当您使用context.become
时,您正在更改演员的行为。这意味着,当演员使用默认的receive
行为启动它时。但是,当它收到消息时,它会打印消息Happens here
并使用部分函数active
来处理它。
因为,在active
里面你调用context.become(active(_))
这个演员的行为改变了。从现在开始,当邮件发送给演员时,它将执行部分功能active
而不是receive
方法,这就是为什么您在输出中不会看到Happens here
多次。
+0
谢谢你,你的回答正是我所看到的。 – eduardo
这不是我所得到的:https://scastie.scala-lang.org/6IdNU8IUTQyj4ZEmyZGStg – rethab