I've encountered a little issue with command handling in Axon 4.
Let say I have an aggregate that need to call an external service when handling a command.
The external service uses an asynchronous client (vertx tcp client + rxjava), so the response is given in a different thread than the one that created the aggregate instance.
I want to apply an event given the result of my service, but it does not work because the AggregateLifecycle.apply()
call is on a different thread...
How can I "transfert" the scope of the aggregate ?
Here is a little exemple of what I want to do (uses rxjava 2 and lombok):
The aggregate:
@Slf4j
@Aggregate
@NoArgsConstructor
public class MyAggregate {
@AggregateIdentifier
private String id;
@CommandHandler
public MyAggregate(CreationCommand creationCommand) {
Single.just("some data")
.observeOn(Schedulers.computation()) // <- comment this line and the test pass, uncomment and it fail because apply is on another thread ?
.subscribe((s, throwable) -> apply(new AggregateCreatedEvent(creationCommand.getId())));
}
@EventSourcingHandler
public void on(AggregateCreatedEvent event) {
this.id = event.getId();
}
}
@Value class CreationCommand { String id; }
@Value class AggregateCreatedEvent { String id;}
And the test:
public class MyAggregateTest {
AggregateTestFixture<MyAggregate> testFixture = new AggregateTestFixture<>(MyAggregate.class);
@Test
public void test() {
testFixture.givenNoPriorActivity()
.when(new CreationCommand("123"))
.expectEvents(new AggregateCreatedEvent("123"));
}
}
Here is the error I've got:
java.lang.IllegalStateException: Cannot request current Scope if none is active