Diego Martinoia
Diego Martinoia

Reputation: 4662

Akka pipe completion priority with onSuccess

In my actor, I do something like:

//upon receiving a message
Future myFuture = Futures.succesful(doSomething());
myFuture.onSuccess(new OnSuccess<Object>() {
            @Override
            public void onSuccess(Object object) throws Throwable {
                doSomethingLong(object);
            }
        }, dispatcher);
Patterns.pipe(myFuture).to(sender());

Will my sender receive the message response at the time where "doSomething()" completes, i.e. as soon as the first future completes, or after the "doSomethingLong()" completes, i.e. after the onSuccess handler operations have completed?

Upvotes: 1

Views: 109

Answers (2)

Viktor Klang
Viktor Klang

Reputation: 26589

In your example, the onSuccess and the pipe will happen concurrently.

If you don't want a possibly failed invocation of doSomethingLong() to affect the outcome, and you want it to have executed before piping it to sender, then I'd suggest the following:

Future myFuture = Futures.successful(doSomething());
Patterns.pipe(myFuture.andThen(new OnComplete<Object>() {
    public void onComplete(Throwable failure, Object result) {
      if (failure != null)
        doSomethingLong(result);
    }
  }, dispatcher)).to(sender());

Upvotes: 1

dvim
dvim

Reputation: 2253

Note that onSuccess is deprecated since Scala 2.12.0. Consider moving to foreach or onComplete

onSuccess attaches a function to be executed when the target future is completed with a value. Therefore the callback and the message send to the actor is going to happen concurrently.

If you want a sequential behaviour, use map instead of onSuccess.

Upvotes: 1

Related Questions