Alifax
Alifax

Reputation: 21

Mutiny - combine Uni and Multi based on business logic

I am new to reactive programming. Kindly assist in achieving the below in Mutiny.

I have a DTO class

public class UserAppSessionDto{
    private UserDto user;
    private List<OrgDto>  userOrgs;
    private List<AppDto> userApps;
}

and 3 service methods, one returning Uni and others returning Multi.

Uni<UserDto> getUserByOrgUserId(Integer orgUserId);
Multi<AppDto> getUserApps(Integer orgUserId);
Multi<RoleDto> getUserRoles(Integer orgUserId);

I need to write a service method which calls the above 3 methods, apply some business validations , set the return values to an instance of UserAppSessionDto and return a Uni<UserAppSessionDto>. I have mentioned the basic business logic (null check) to be applied below.

public Uni<UserAppSessionDto> getUserAppSessionDetails(Integer orgUserId)
         {
             UserAppSessionDto user=new UserAppSessionDto();

             //1. call the method Uni<UserDto> getUserByOrgUserId(Integer orgUserId)
             //2. If UserDto (in the returned Uni) is not null, call Multi<AppDto> getUserApps(Integer orgUserId) and Multi<RoleDto> getUserRoles(Integer orgUserId) methods in parallel. 
             //3. Set the return values from the above three methods into user variable
             //4. Return Uni<UserAppSessionDto>

             return Uni.createFrom().item(user);
         }

Upvotes: 2

Views: 3665

Answers (1)

Clement
Clement

Reputation: 3192

Any reason why getUserApps and getUserRoles are returning Multis? I don't believe they will stream the results, but instead, return the list in one batch. If that's the case, using Uni<List<X> is better.

With this change, you logic becomes a lot easier:

public Uni<UserAppSessionDto> getUserAppSessionDetails(Integer orgUserId) {
  UserAppSessionDto user=new UserAppSessionDto();

 Uni<UserDto> uni = getUserByOrgUserId(orgUserId)
       .invoke(userDTO -> user.user = userDTO);
 
return uni
   onItem().ifNotNull().transformToUni(userdto -> 
       Uni.combine().all()
         .unis(getUserApps(orgUserId),getUserRoles(orgUserId))
         .asTuple()
         .invoke((apps, roles) -> user....)
     )
     .map(x -> user);
}

Upvotes: 2

Related Questions