Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax to store results of previous mapping

I would like to know the good way to use results of previous mapping in spring web-flux, for example

Mono.just(request)
...
.flatMap(object0 -> createObject1(object0))
.flatMap(object1 -> createObject2(object1))
...

what a good way to get object0 at this point, so we could add something like

.flatmap(object0 -> createResult(object0))

I solved it by uniting this both method so that we have object0 in global variable, but it doesn't looks good.

Another example

Mono.just(request)
...
.flatMap(object0 -> createResponse(object))
.map(result -> mapToObject1(result))
.flatMap(object1-> saveObject1(object1))

How to return "result" at this point?

Could you please give link to good example of same cases, because solution to unite this line to make result global doesn't looks good as it creates ambiguous methods?

like image 578
Evgen Avatar asked Mar 11 '26 20:03

Evgen


2 Answers

You can wrap several objects into a reactor.util.function.Tuples, like this:

Mono.just(request)
...
.flatMap(object0 -> Tuples.of(object0, createObject1(object0)))
.flatMap(tuple -> createObject2(tuple.getT2()))
...

I don't know if it's really a best practice here, because your code snippet is very generic and I can't say whether it's an issue with the underlying API.

like image 93
Brian Clozel Avatar answered Mar 15 '26 02:03

Brian Clozel


For the first case, because you are using flatMap for createObject1(object0), I assume that it is returning Mono<Object1> , I think the following code snippet can do what you wanted.

    public Mono<Class1> createObject1(Class0 object0) {
        //...
    }

    public Mono<Class2> createObject2(Class1 object1, Class0 object0) {
        //...
    }

    public void test() {
        Mono.just(new Class0())
        .flatMap(object0 -> createObject1(object0).zipWith(Mono.just(object0)))
        .flatMap(tuple -> createObject2(tuple.getT1(), tuple.getT2()));
    }

For the second case, as the accepted answer suggested, using reactor.util.function.Tuples in map will do.

like image 26
chao_chang Avatar answered Mar 15 '26 02:03

chao_chang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!