Nitin1706
Nitin1706

Reputation: 659

How to return an object from Mono SpringWebFlux

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'

Upvotes: 5

Views: 18131

Answers (2)

Toerktumlare
Toerktumlare

Reputation: 14820

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

Upvotes: 2

Michael Berry
Michael Berry

Reputation: 72379

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.

Upvotes: 5

Related Questions