1

I would like to do something like this:

if (someObject == null) {
    return Mono.just(someId)
      .flatMap(si -> service.monoVoidMethod(si));
}
return Mono.just(someObject)
        .flatMap(so -> service.monoObjectMethod(so)
             .flatMap(so2 -> service.monoVoidMethod2(so2)))

it's any way to do it in more 'reactive way', without that if statement? I have tried with Mono.switchIfEmpty, but its turns that both monoVoidMethod and monoVoidMethod2 was called when someObject wasn't null.

return Mono.justOrEmpty(someObject)
   .flatMap(so -> service.monoObjectMethod(so)
             .flatMap(so2 -> service.monoVoidMethod2(so2)))
   .switchIfEmpty(Mono.empty().flatMap(var -> service.monoVoidMethod(si)))
     

I found a twin topic: Mono switchIfEmpty() is always called

and tried also with Mono.defer, but nothing changed:

return Mono.justOrEmpty(someObject)
   .flatMap(so -> service.monoObjectMethod(so)
             .flatMap(so2 -> service.monoVoidMethod2(so2)))
   .switchIfEmpty(Mono.defer(() -> service.monoVoidMethod(si)))

everything works well, when monoVoidMethod2 and monoVoidMethod1 isnt Void type - but this is not my case. In my system monoVoidMethod2 and monoVoidMethod1 returns http status with empty body.

kigeb63101
  • 11
  • 3

1 Answers1

0

Your example has no error. Here you go

   public void test(Integer integer) {
        Mono.justOrEmpty(integer)
                .flatMap(so -> Mono.just(1)
                         .flatMap(so2 -> Mono.just(3)))
                .switchIfEmpty(Mono.just(10))
                .subscribe(System.out::println);
    }

If you execute test(1) then it'll print 3. Anotherway, executing test(null) returns a 10 - switchIfEmpty value.

--- Updated at 30.01.2021

I've been changed test. flatMap for so2 returns an empty Mono. So, both invocations test(1) and test(null) return 10

public void test(Integer integer) {
   Mono.justOrEmpty(integer)
      .flatMap(so -> Mono.just(1)
         .flatMap(so2 -> Mono.empty()))
      .switchIfEmpty(Mono.just(10))
      .subscribe(System.out::println);
}
Timur
  • 51
  • 6
  • thats because ur example is a bit different. U returning Mono.just(3) [Mono], instead of Mono Try with exacly the same as mine – kigeb63101 Jan 29 '21 at 08:33
  • @kigeb63101 In your example a `flatMap` for so2 return an response with empty body, it triggers a `onNext` signal. But, the switchIfEmpty works when it is got a onComplete signal. – Timur Jan 30 '21 at 06:39
  • @kigeb63101 you need to change your `flatMap(so2 -> service.monoVoidMethod2(so2)))` to `flatMap(so2 -> service.monoVoidMethod2(so2)).then())`. After that `switchIfEmpty` will be invoked – Timur Jan 30 '21 at 06:42
  • I also tried that. Even with then() if my object isn't null, both monoVoidMethod2 and switchIfEmpty are executed. – kigeb63101 Jan 30 '21 at 17:42