How to return an object from Mono SpringWebFlux
Asked Answered
D

2

5

I am using Spring Webflux, and I need to return the ID of user upon successful save.

Repository is returning the Mono

Mono<User> savedUserMono = repository.save(user);

But from controller, I need to return the user ID which is in object returned from save() call.

I have tried using doOn*, and subscribe(), but when I use return from subscribe, there is an error 'Unexpected return value'

Drama answered 6/8, 2019 at 17:7 Comment(2)
Possible duplicate of How to get username from mono<user> on spring boot webflux?Sirreverence
see this one #57019589Bergstein
K
5

Any time you feel the need to transform or map what's in your Mono to something else, then you use the map() method, passing a lambda that will do the transformation like so:

Mono<Integer> userId = savedUserMono.map(user -> user.getId());

(assuming, of course, that your user has a getId() method, and the id is an integer.)

In this simple case, you could also use optionally use the double colon syntax for a more concise syntax:

Mono<Integer> userId = savedUserMono.map(User::getId);

The resulting Mono, when subscribed, will then emit the user's ID.

Katydid answered 7/8, 2019 at 7:43 Comment(0)
B
2

what you do is

Mono<String> id = user.map(user -> {
        return user.getId();
    });

and then you return the Mono<String> to the client, if your id is a string

Baudoin answered 6/8, 2019 at 22:4 Comment(4)
User<String> id should be a Mono<String> idMoussaka
yes thank for pointing it out, was a bit too fast there. i have edited itBaudoin
for readability I'd recommend using method reference: user.map(User::getId)Prothrombin
for readability id say this is more readable, your suggestion is less readable but what i prefer. But since the thread starter doesn't seam to have much experience the more verbose version above is more understandable.Baudoin

© 2022 - 2024 — McMap. All rights reserved.