Perform operation on a flux element based on previous element result

  Kiến thức lập trình

I have three classes of type Work like below.

interface Work{
        boolean execute();
    }

    class Service1 implements Work{

        @Override
        boolean execute(){
            //some complex logic
            return true;
        }
    }

    class Service2 implements Work{

        @Override
        boolean execute(){
            //some complex logic
            return true;
        }
    }

    class Service3 implements Work{

        @Override
        boolean execute(){
            //some complex logic
            return true;
        }
    }

I want to stream each of these from a list as flux and execute the next service only if the current element’s execute method returns true.

Service1 service1 = new Service1();
Service2 service2 = new Service2();
Service3 service3 = new Service3();
List<Work> serviceList = List.of(service1, service2, service3);
Flux<Work> services = Flux.fromStream(serviceList.stream());

//?? how to process the next element based on current element's result

I could do this with the Mono by chaining through flatMap like below, but I wanted to achieve this using Flux.

Mono<Work> service1Mono = Mono.just(service1);
Mono<Work> service2Mono = Mono.just(service2);
Mono<Work> service3Mono = Mono.just(service3);
Mono<Work> workResult = service1Mono.flatMap(a->{
  if(a.execute())
       return service2Mono;
  return Mono.just(a);
}).flatMap(b -> {
  if(b.execute())
        return service3Mono;
  return Mono.just(b);
});
//do something with the workResult

New contributor

inder kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT