Skip to content
Advertisement

Java Spring Webflux – inserting an empty Mono result of a filter?

Small question please: Does it make sense to save an empty Mono, by that, I mean the result of a filter on a Mono, into a reactive database please?

A small sample:

        // step 1 - from some Mono, compute my pojo
        final Mono<MyPojo> myPojoMono = getSomeMonoAndConvertToMyPojo();

        // step 2 - based on a predicate, some myPojo are invalid, I do not want to save them, but some are valid, I need to persist them!
        final Mono<MyPojo> validMyPojoMono = myPojoMono.filter(oneMyPojo -> computeIsValidMyPojo(oneMyPojo));

        // step 3 - for those who are valid only, I want to persist them. BTW, should I use something else other than .insert(Publisher) which strangely, returns a flux?
        final Flux<PdsResponse> whyFlux  = myReactiveRepository.insert(validMyPojoMono);
        return whyFlux;

After step 2, if the predicate does not match, (not sure) the result will be an empty mono.

Hence, does it make sense to invoke the persistence API on an empty mono please?

What is the appropriate way to achieve this use case please?

Thank you

Advertisement

Answer

You code is kind of sync and I am not sure if it make sense.

I would do this way

final Mono<MyPojo> myPojoMono = getSomeMonoAndConvertToMyPojo()
    .filter(oneMyPojo -> computeIsValidMyPojo(oneMyPojo));
    .flatMap(validMyPojoMono-> reactiveRepository.insert(validMyPojoMono));

The point is that if after filter you get empty mono then it wont persist which make sense to me.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement