Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactor : How to convert a Flux of entities into a Flux of DTO objects

I have a User entity and a Role entity. The fields are not important other than the fact that the User entity has a role_id field that corresponds to the id of its respective role. Since Spring Data R2DBC doesn't do any form of relations between entities, I am turning to the DTO approach. I am very new to R2DBC and reactive programming as a whole and I cannot for the life of me figure out how to convert the Flux<User> my repository's findAll() method is returning me to a Flux<UserDto>. My UserDto class is extremely simple :

@Data
@RequiredArgsConstructor
public class UserDto 
{
    private final User user;

    private final Role role;
}

Here is the UserMapper class I'm trying to make :

@Service
@RequiredArgsConstructor
public class UserMapper 
{
    private final RoleRepository roleRepo;

    public Flux<UserDto> map(Flux<User> users)
    {
        //???
    }
}

How can I get this mapper to convert a Flux<User> into a Flux<UserDto> containing the user's respective role?

Thanks!

like image 693
Martin Avatar asked Nov 04 '19 03:11

Martin


People also ask

How do you convert flux objects to Mono?

Instead of take(1) , you could use next() . This will transform the Flux into a valued Mono by taking the first emitted item, or an empty Mono if the Flux is empty itself.

How do you get data from flux?

How to extract data from Flux in Java? Another way would be using the Reactive Streams operators like onNext, flatMap, etc. In the below example, we are using the onNext() method to get data from Flux and print it. Note: We need to subscribe to the Publisher.

What is flux in reactor?

Mono and Flux are both reactive streams. They differ in what they express. A Mono is a stream of 0 to 1 element, whereas a Flux is a stream of 0 to N elements.

How does mono and flux work?

In this article I will discuss how Mono and Flux work when you define set of operations on it and subscribe to it. new FluxMapFuseable<>(this, mapper); Now the flux array becomes the source publisher for this FluxMap which is correct if you think about it. On the second call to Flux.


Video Answer


1 Answers

Assuming your RoleRepository has a findById() method or similar to find a Role given its ID, and your user object has a getRoleId(), you can just do it via a standard map call:

return users.map(u -> new UserDto(u, roleRepo.findById(u.getRoleId())));

Or in the case where findById() returns a Mono:

return users.flatMap(u -> roleRepo.findById(u.getRoleId()).map(r -> new UserDto(u, r)));

You may of course want to add additional checks if it's possible that getRoleId() could return null.

like image 111
Michael Berry Avatar answered Oct 20 '22 00:10

Michael Berry