2017-07-19 84 views
0

我正在學習如何使用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在我的演員,阿卡如何以及何時在第一個之後處理消息?

+0

這不是我所得到的:https://scastie.scala-lang.org/6IdNU8IUTQyj4ZEmyZGStg – rethab

回答

3

當您使用context.become時,您正在更改演員的行爲。這意味着,當演員使用默認的receive行爲啓動它時。但是,當它收到消息時,它會打印消息Happens here並使用部分函數active來處理它。

因爲,在active裏面你調用context.become(active(_))這個演員的行爲改變了。從現在開始,當郵件發送給演員時,它將執行部分功能active而不是receive方法,這就是爲什麼您在輸出中不會看到Happens here多次。

+0

謝謝你,你的回答正是我所看到的。 – eduardo