Search code examples
javadictionaryfilterchainingreactor

Chaining Java Reactor Monos with filter and Map


I am trying to call multiple services (using Java Reactor) and the output of one service would determine whether the next service should be called or not.

  1. Validate that the session is valid by calling validateSession API
  2. Check If the session is valid and and has a login associated to it
  3. Fetch the details for the login
  4. Check if the login details has first name in it
  5. If all the above passes, then generate the credentials

The line

.filter(details -> details != null && StringUtils.isNotBlank(details.getFName))

gives error since "details" is being interpreted as a Mono.

If I change the code to use flatMap instead of Map, it works fine but I want a synchronous response as I need to wait for everything to complete before I can generate credentials.

.map(session -> dao.getDetails(session.getLogin()))
                .filter(details -> details != null && StringUtils.isNotBlank(details.getFName))

Below is the code having issue.

Mono<Credentials> response = dao.validateSession(sessionId)
                .filter(session -> session != null && StringUtils.isNotBlank(session.getLogin()))
                .map(session -> dao.getDetails(session.getLogin()))
                .filter(details -> details != null && StringUtils.isNotBlank(details.getFName))
                .map(details -> dao.generateCredentials())
                .cast(Credentials.class);

Solution

  • You can simplify like this:

    Mono<Credentials> response = dao.validateSession(sessionId)
                    .filter(session -> StringUtils.isNotBlank(session.getLogin()))
                    .flatMap(session -> dao.getDetails(session.getLogin()))
                    .filter(details -> StringUtils.isNotBlank(details.getFName))
                    .flatMap(details -> dao.generateCredentials());
    

    I've changed the operator used to simplify, but I think the last step require the details object to be used as arguments of generateCredentials method.