command callback execution within gateway

Hi,
I’m using this simple code to initialize application with commands:

commandGateway.send(command, new CommandCallback<Object>() {
   @Override
   public void onSuccess(Object result) {
      saveWithState(processingEntity, CommandInitializerState.EXECUTED);
   }

   @Override
   public void onFailure(Throwable cause) {
      saveWithState(processingEntity, CommandInitializerState.FAILED);
      logger.error("Failed to process command ", cause);
   }
});

it some cases, there are operations which performs on same aggregate (e.g. CreateAccountCommand, AddAccountOptionCommand)
In this cases there comes an issue while using AsynchronousCommandBus that when I invoke second command, the aggregate is still not persisted, so I see something like ???aggregate with id [xyz] does not exists???
how to perform this operation while waiting for result? Do I need to use FutureCallback. Any example in there?

I’m stiil on axon 2.4. and using my own gateway interface.

Thanks

use it like this…

`

public class CompleteableFutureCallback<R> implements CommandCallback<R> {

    @Getter
    private CompletableFuture<R> future = new CompletableFuture<R>();

    @Override
    public void onSuccess(R result) {
        future.complete(result);
    }

    @Override
    public void onFailure(Throwable cause) {
        future.completeExceptionally(cause);
    }
}

CompleteableFutureCallback callback = new CompleteableFutureCallback();commandGateway.send(command, callback);
callback.getFuture().thenAccept(e -> {
//execute on other thread on accepted
});

`

Hi,
that’s nice. As I don’t have experience with CompletableFutures, is this code ok?

CommandInitializerCallback<Object> callback = new CommandInitializerCallback();
commandGateway.send(command, callback);
callback.getFuture()
      .handle((ok, exception) -> {
         if (ok != null) {
            saveWithState(processingEntity, CommandInitializerState.EXECUTED);
         } else {
            saveWithState(processingEntity, CommandInitializerState.FAILED);
            logger.error("Failed to process command ", exception);
         }
         return ok;
      });

It looks allright. Note that the callback may be invoked asynchronously, depending on the CommandBus implementation you’re using. This may also mean there is no active transaction when the saveWithState is invoked.

Note that the CommandGateway in Axon 3 will return a CompletableFuture on the send(command) method, so that the use of callbacks isn’t required for those cases anymore.

Cheers,

Allard