SkyBlue
SkyBlue

Reputation: 277

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

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;

}  

Upvotes: 6

Views: 3616

Answers (1)

kj007
kj007

Reputation: 6254

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

Upvotes: 2

Related Questions