ace
ace

Reputation: 12024

How to return after successful return from subscribe within flatMap in spring reactor web app?

Below code compiles fine:

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ........

 .flatMap(user-> {
            userRepository.save(user).subscribe();
            return chain.filter(exchange);
  });

......

chain.filter(exchange) whose return type is Mono(Void) delegates to the next web filter in the chain.

But I need to invoke the line return chain.filter(exchange); after successful completion of userRepository.save otherwise it fails to save the user when next webfilter runs.

I tried below code but it does not even compile.

.flatMap(user-> {
userRepository.save(user).subscribe(u -> chain.filter(exchange) );

}); 

How to fix this problem?

Upvotes: 1

Views: 1255

Answers (1)

Yauhen Balykin
Yauhen Balykin

Reputation: 771

Try this:

return
...
.flatMap(userRepository::save)
.then(chain.filter(exchange));

1) Combine calling filter and userRepository to one chain;

2) If userRepository::savecaused error, data emits will be stopped and request aborted, otherwise then() will call chain.filter(exchange).

Upvotes: 1

Related Questions