如何订阅Mono<Mono<Object>>?Reactor嵌套Mono处理问询
Hey there! I totally get why that double subscribe feels clunky—let's clean this up properly. The issue here is that your current code returns a nested Mono (Mono<Mono<Object5>>) because the lambda inside the outer Mono.zip produces another Mono. We need to "flatten" this structure to get a single Mono<Object5> instead.
Solution 1: Use flatMap to Unwrap the Nested Mono
The simplest fix is to add a flatMap operator after your outer Mono.zip. Since flatMap expects a function that returns a Mono, it will automatically subscribe to that inner Mono and pass its result downstream:
Mono<Object1> oneMono = Mono.just("1"); Mono<Object2> twoMono = Mono.just("2"); // This gives us a clean Mono<Object5> Mono<Object5> resultMono = Mono.zip(oneMono, twoMono, (one, two) -> { Mono<Object3> threeMono = Mono.just("3"); Mono<Object4> fourMono = Mono.just("4"); return Mono.zip(threeMono, fourMono, (three, four) -> "5"); }).flatMap(innerMono -> innerMono); // Or use Function.identity() for brevity
Solution 2: Refactor to Use Chainable Operators (More Idiomatic)
For a cleaner, more idiomatic Reactor style, you can restructure the code to use zipWith and chain flatMap directly, avoiding nested lambdas altogether:
Mono<Object1> oneMono = Mono.just("1"); Mono<Object2> twoMono = Mono.just("2"); Mono<Object5> resultMono = oneMono.zipWith(twoMono) .flatMap(outerTuple -> { // Access the results from the first zip: outerTuple.getT1() and outerTuple.getT2() Mono<Object3> threeMono = Mono.just("3"); Mono<Object4> fourMono = Mono.just("4"); return threeMono.zipWith(fourMono) .map(innerTuple -> { // Process innerTuple.getT1() and innerTuple.getT2() if needed return "5"; }); });
Why This Works
flatMap is designed exactly for this scenario: it handles asynchronous operations that produce another reactive type (like a Mono or Flux) by unwrapping it, so you never end up with nested publishers. This keeps your reactive stream flat and avoids the need for manual double subscriptions.
Now you can subscribe to resultMono directly, no nested calls required:
resultMono.subscribe(result -> System.out.println("Got result: " + result));
内容的提问来源于stack exchange,提问作者Aleksey Kozel

