2016-06-11 62 views
1

父母子女在父母向孩子發送消息並且孩子以值1迴應的父孩子中,但父母沒有收到該值,因爲消息「received」是1「不會打印到控制檯。Akka父母未收到來自子女的消息

我的層次設置是否正確? :

import akka.actor.Actor 
import akka.actor.ActorSystem 
import akka.actor.Props 

class ChildActor extends Actor { 
    def receive = { 
    case receivedValue: Int => { 
     println(receivedValue); 
     context.parent ! 1 
    } 
    } 
} 

object ParentChild extends App { 

    val system = ActorSystem() 

    val parentActor = system.actorOf(Props[ParentActor]) 

    class ParentActor extends Actor { 

    val childActor = system.actorOf(Props[ChildActor]) 
    childActor ! 1 
    def receive = { 
     case v: Int => println("received is " + v); 
    } 

    } 

} 
+0

你在哪裏發送信息給Child actor? – curious

+1

問題是小孩的演員其實並不是父母的孩子,演員不會成爲小孩演員就是在父母身上創造一個引用,實際上你需要在父母的背景下創建一個引用。因此,不需要'system.actorOf(Props [ChildActor])''你需要執行'context.actorOf(Props [ChildActor])'。 – curious

+0

@curious那個工作,如果投入回答不好接受 –

回答

2

因爲你使用

val childActor = system.actorOf(Props[ChildActor])

這意味着它是一個頂級演員創造的childActor,它的母公司是ActorSystem代替ParentActor,你會期望

要如預期那樣工作,您需要按照以下步驟創建ChildActor:

val childActor = context.actorOf(Props[ChildActor])

inside ParentActor