ShaggyInjun
ShaggyInjun

Reputation: 2963

Working with spring webflux reactive repositories results in nested Mono Object

public interface ApplicationDataRepository extends ReactiveCrudRepository<ApplicationData, Long> {
}

Working with spring webflux reactive repositories results in nested Mono Object.

applicationDataRepository.findById(100L).map(o -> {
    o.setName("changed name");
    return applicationDataRepository.save(o);
})

The above three lines of code results in Mono<Mono<ApplicationData>>. How can I transform this into Mono<ApplicationData> or avoid ending up in this situation ?

Upvotes: 0

Views: 832

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121262

It's not WebFlux matter. It is a Reactive Streams programming model and its API implementation via Project Reactor. Please, make yourself familiar with it first of all: https://projectreactor.io/

What you need is a flatMap operator of the Mono:

/**
 * Transform the item emitted by this {@link Mono} asynchronously, returning the
 * value emitted by another {@link Mono} (possibly changing the value type).
 *
 * <p>
 * <img class="marble" src="doc-files/marbles/flatMapForMono.svg" alt="">
 *
 * @param transformer the function to dynamically bind a new {@link Mono}
 * @param <R> the result type bound
 *
 * @return a new {@link Mono} with an asynchronously mapped value.
 */
public final <R> Mono<R> flatMap(Function<? super T, ? extends Mono<? extends R>>
        transformer) {

https://projectreactor.io/docs/core/release/reference/#which.values

The WebFlux is really just about a Web: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#spring-webflux

The ReactiveCrudRepository is a part of Spring Data project: https://docs.spring.io/spring-data/commons/docs/2.4.6/reference/html/#repositories

What I mean that it is wrong to call everything "webflux" since the subject is a bit broader than just Web.

Upvotes: 1

Related Questions