Reputation: 659
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
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
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