简体   繁体   中英

Sending message to child actor on parent and wait result

I am trying to send message to child actor from parent but the message doesnot arrive until parent actor completes the onReceive block. Is the any way to send message to child and wait result on the parent actor.

Parent:
onReveive(message) {
    if(message instanceof ChildOrder) {
        onChildOrder(message);
    }
}

onChildOrder(message) {
    Future<Object> future = Patterns.ask(childActorRef, order, timeout);
    Object result = Await.result(future, timeout.duration()); /* this always times out */ 
}

Child:
onReveive(message) {
    do stuff
}

As mentioned above Object result = Await.result(future, timeout.duration()); line on onChildOrder method always times out and when the onReceive method of parent completes the message ChildOrder arrives at the child's onReceive method.

It seems child cannot process any message without parent completes first.

Is there any way to send message to child and wait result. ?

You need the child to send the result back to the parent, otherwise the parent keeps waiting for an answer forever.

In Child:

@Override
public void onReceive(Object message) throws Exception {
    MyResult res = doStuff(message);
    // send result back
    getSender().tell(res, getSelf());
}

It is indicated in the documentation of Patterns.ask :

[...] this means that the target actor needs to send the result to the sender reference provided.


Edit based on the comment:

Forward message from grandfather to child:

If you need the child to send back to the grand-parent, the parent may forward the message to the child so that to the child the sender is the grand-parent, therefore bypassing the parent on the way back:

In parent:

@Override
public void onReceive(Object message) throws Exception {
    if(message instance of MessageFromGrandParent) {
        child.forward(message, getContext());
    }
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM