Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value from Mono/Flux to methods

I'm new to reactive programming concept. I'm following the "Learning Spring Boot 2.0" and the described simple concepts/examples are understandable. But I don't get how to use Mono/Flux in more complex use cases. Some example with with spring boot, mongo and project reactor

My model

User
@Id
private String id;
private String login;

Comment
@Id
private ObjectId _id;
private String content;
private String ownerLogin;

so this simple example to get comments by owner works fine

@GetMapping(params = "login")
@ResponseBody
public Flux<Comment> getAllCommentsByLogin(@RequestParam("login") String login) {
    return commentRepository.findByOwnerLogin(login);
};

But if I would slightly change the model to store owner by entity id, it would be not so ease to retrieve the comments by owner

Comment
@Id
private ObjectId _id;
private String content;
private String ownerId;

my intention is to make rest controller easy to use by end user and first find the user entity by login and if exists all user comments

@GetMapping(params = "login")
@ResponseBody
public Flux<Comment> getAllCommentsByLogin(@RequestParam("login") String login) {
    return commentRepository.findByOwnerId(userRepository.findByLogin(login).map(user2 -> user2.getId())
};

this soulution is obviously wrong, but I don't know if the whole approach is wrong or only this method.

like image 883
dezerb Avatar asked Nov 17 '25 16:11

dezerb


1 Answers

Let's hope your userRepository.findByLogin() returns Mono<User>, then code should be like this:

return userRepository.findByLogin(login)
               .flatMapMany(user -> commentRepository.findByOwnerId(user.getId()));
like image 86
Artem Bilan Avatar answered Nov 20 '25 06:11

Artem Bilan



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!