javaquarkusvert.xmutiny

quarkus @ObservesAsync invoke Uni


What's the best way to invoke Uni in an async observer? It would be great if I could just return Uni but unfortunately that doesn't work.

void observe(@ObservesAsync MyEvent event) {
    Uni<Object> task;
}

Solution

  • As mentioned by @ladicek, you can:

    1. use a synchronous observer and block until termination
    2. use a synchronous observer and "trigger" the async operation using a fire-and-forget approach
    3. use an async observer (while it's not strictly async, it just runs on another thread) and produce a CompletionStage

    1) Synchronous observer and block until termination

    void observe(@Observes MyEvent event) {
        Uni<Void> uni = ...;
        uni.await().indefinitely();
    }
    

    2) Synchronous observer and trigger the async operation using a fire-and-forget approach

    void observe(@Observes MyEvent event) {
        Uni<Void> uni = ...;
        uni.subscribeAsCompletionStage(); // Fire and forget, no error reporting
    }
    

    Or:

    void observe(@Observes MyEvent event) {
        Uni<Void> uni = ...;
        uni.subscribe().with(success -> ..., failure -> log(failure));
    }
    

    3) Async observer and produce a CompletionStage

    CompletionStage<Void> observe(@ObservesAsync MyEvent event) {
        Uni<Void> uni = ...;
        return uni.subscribeAsCompletionStage();
    }