我正在學習如何使用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在我的演員,阿卡如何以及何時在第一個之後處理消息?
這不是我所得到的:https://scastie.scala-lang.org/6IdNU8IUTQyj4ZEmyZGStg – rethab