问题描述:

I dont understand this statement about closing over the actor ref in the callback.

Currently I am using

public void onReceive(Object message) throws Exception {

ActorRef senderActorRef = getSender(); //never close over a future

if (message instanceof String) {

Future<String> f =akka.dispatch.Futures.future(new Callable<String>() {

public String call() {

String value= jedisWrapper.getString("name");

senderActorRef.tell((String) message,ActorRef.noSender());

return "what";

}

}, ex);

f.onSuccess(new OnSuccessExtension(), ex);

}

}

private final class OnSuccessExtension extends OnSuccess {

@Override

public void onSuccess(Object arg0) throws Throwable {

log.info("what");

}

}

Is this the right way to use it?

How can I pass the Sender Actor ref in the OnSuccess method?

Also whats the difference between onSuccess and OnComplete ?

If I want to use onComplete how would I use it?

Answer: Pass the Sender Actor Ref in the constructor. The answer given by another user.

OnSuccess is a specialized form of OnComplete.

OnComplete useage from Akka docs

final ExecutionContext ec = system.dispatcher();

future.onComplete(new OnComplete<String>() {

public void onComplete(Throwable failure, String result) {

if (failure != null) {

//We got a failure, handle it here

} else {

// We got a result, do something with it

}

}

}, ec);

网友答案:

Pass it in the constructor:

public void onReceive(Object message) throws Exception {
    final ActorRef senderActorRef = getSender(); //never close over a future
    if (message instanceof String) {
        Future<String> f = // ...
        f.onSuccess(new OnSuccessExtension(senderActorRef), ex);
    }
}

private final class OnSuccessExtension extends OnSuccess {
    private final ActorRef senderActorRef;

    public OnSuccessExtension(ActorRef senderActorRef) {
        this.senderActorRef = senderActorRef;
    }

    @Override
    public void onSuccess(Object arg0) throws Throwable {
        log.info("what");
        // use senderActorRef
    }
}
相关阅读:
Top