Ray Zhang
Ray Zhang

Reputation: 1561

Asynchronous Java: Help flatten my nested Mono

Setup:

public Mono<Mono<String>> getAsyncResult() { // should return Mono<String>
    return Mono.fromSupplier(() -> {
        if (stopEarly()) return Mono.just("STOPPED EARLY");

        int a = doSyncJob1();
        int b = doSyncJob2();
        return doAsyncJob(a, b).map(string1 -> toString2(string1));
    });
}

Right now the whole thing returns Mono<Mono<String>>. How to get it to return Mono<String> without blocking?

The reason it's all inside Mono.fromSupplier() is because I don't need the tasks to necessarily block and happen immediately, they can be scheduled to run asynchronously. Maybe one way is to flatten what's inside Mono.fromSupplier() but I'm not sure how to compose it.

Upvotes: 1

Views: 1180

Answers (1)

Phil Clay
Phil Clay

Reputation: 4554

Replace Mono.fromSupplier with Mono.defer

Also, if doSyncJob* blocks, then they will block the subscriber thread. Therefore, you might want to use .subscribeOn(Schedulers.elastic()) after .defer(...) to ensure the blocking work is executed in a Scheduler meant for blocking work.

Upvotes: 4

Related Questions