Morteza Malvandi
Morteza Malvandi

Reputation: 1724

How use thenEmpty and then thenReturn in Spring WebFlux?

I'm new in Spring WebFlux and I have a problem. I want to return something like Mono<String> as follow:

@PostMapping("/test")
public Mono<String> test(){
    return Mono.just("Test String")
           .thenEmpty(it -> {
                // Do something I need
                System.out.println("Print somethings");
           })
           .thenReturn("Return String");
}

I wish the method to return Return String, But it return nothing. What's the Problem?

Upvotes: 1

Views: 8062

Answers (2)

Gnana
Gnana

Reputation: 2230

thenEmpty will be invoked and return Mono<Void> as part of pipeline order. since Mono<Void> return, rest of the operator in pipeline is not working. if you want to use thenReturn then use below code.

@PostMapping("/test")
public Mono<String> test(){
    return Mono.just("Test String")
           .doOnNext(s -> {
                    // do what you want
                })
           .thenReturn("Return String");
}

Upvotes: 2

firegloves
firegloves

Reputation: 5709

you can try something like this:

   @PostMapping("/test") public Mono<String> test(){
        return Mono.just("Test String")
                .doOnNext(s -> {
                    // do what you want
                })
                .map(s -> {
                    return "done";
                });
   }

You can use other doOn* methods, depending on what you need. For example doOnSuccess or doOnError.

Then you can use map if you need to manipulate your data (but keeping return type).

Upvotes: 0

Related Questions