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'

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

User<String> id should be a Mono<String> id
yes thank for pointing it out, was a bit too fast there. i have edited it
for readability I'd recommend using method reference: user.map(User::getId)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.