How to modify atributes of a Mono object without blocking it in Spring boot
Asked Answered
S

1

6

I have recently started using reactive and created a simple application which uses reactive streams.

I have the following code which I get an employee by empID. I have to provide extra details about the emplyee to my API only if it is specifically requested when showExtraDetails boolean is set to true. If it's set to false I have to set extra details to null before returning the employee object. Right now I am using a a block on the stream to achieve this. Is it possible to do this without block so my method can return a Mono.

Following is the code I have done.

public Employee getEmployee(String empID, boolean showExtraDetails) {


    Query query = new Query();

    query.addCriteria(Criteria.where("empID").is(empID));


    Employee employee = reactiveMongoTemplate.findOne(query, Employee.class, COLLECTION_NAME).block();


    if (employee != null) {

        logger.info("employee {} found", empID);
    }


    if (employee != null && !showExtraDetails) {

        employee.getDetails().setExtraDetails(null);
    }

    return employee;

}  
Snafu answered 19/9, 2018 at 16:9 Comment(0)
C
2

Try this, should work like this, assuming reactiveMongoTemplate is your mongo repository

return reactiveMongoTemplate.findById(empID).map(employee -> {
            if (!showExtraDetails) {
              employee.getDetails().setExtraDetails(null);
            }
            return employee;                
        });
Clearance answered 19/9, 2018 at 16:41 Comment(4)
you don't need flatMap here, map would do the same job as well. reactiveMongoTemplate.findById(empID).map(employee ->employee.getDetails().setExtraDetails(null))Photocomposition
In the empty case, the map operator is not executed, so map here is a good choice.Apperception
Does that mean I don't have to do a separate null check? @BrianClozelSnafu
per reactive streams spec, a Mono or a Flux is not allowed to provide null elements. So a Mono either provides an element, or nothing (Mono.empty())Apperception

© 2022 - 2024 — McMap. All rights reserved.