Sharing Mono with the publish method doesn't work as expected

Viewed 64

I have two service calls. The second one accepts a value that the first returns. I need to return the result of the first call only if the second succeeds. The following is my prototype implementation, however, the resulting mono is always empty. Please explain why it doesn't work and how to implement it the proper way.

@Test
public void testPublish() {
    callToService1().publish(
        mono -> mono.flatMap(resultOfCall1 -> callToService2(resultOfCall1))
        .then(mono)
        )
        .map(Integer::valueOf)
        .as(StepVerifier::create)
        .expectNext(1)
        .verifyComplete();
    }

Mono<String> callToService1() {
        return Mono.just("1");
}

Mono<Integer> callToService2(String value) {
      // parameter that used in a call to service2
      return Mono.empty();
}
1 Answers

Not sure why you used publish(Function). Sounds like your requirement would be fulfilled by a simple direct flatMap:

callToService1()
    .flatMap(v1 -> callToService2(v1)
        .thenReturn(v1)
    );

if callToService2 throws or produces an onError, that error will be propagated to the main sequence, terminating it.

(edited below for requirement of emitting value from service1)

otherwise, inside the flatMap the callToService2 is completed then we ignore the result and emit the still in scope v1 value thanks to thenReturn (which also propagates onError if callToService2 emits onError)

Related