Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

java - Mono switchIfEmpty() is always executed

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.

question from:https://stackoverflow.com/questions/65944904/mono-switchifempty-is-always-executed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...