简体   繁体   中英

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.

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM