Search code examples
javareactor

Smart way to handle nested flux operations


I have 2 query methods (findByName/findAnotherName) .

Both of them return Mono<List> .

I do some logic by compare results of these two methods, and then return one of them in a nested Flux operation.

It may have a smart way to achieve same result though.

Following is code snippet:

private Mono<List<Student>> find(String name) {

    return repo.findByName(name)
            .flatMap((List<Student> students) -> {

                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap((List<Student> anotherStudents) -> {

                            //do some logic

                            return Mono.just(students);
                        });

            });

}

Thanks in advance.


Solution

  • https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#zipWhen-java.util.function.Function-java.util.function.BiFunction-

    If your //do some logic is sync then I can suggest something like

    private Mono<List<Student>> find(String name) {
    
        return repo.findByName(name)
                .zipWhen((List<Student> students) -> {
                    return repo.findAnotherName(anothName, 1).collectList();
                }, (students, anotherStudents) -> {
                    //some sync logic
                    return students;
                });
    }
    

    But if the logic is also async, then

    private Mono<List<Student>> find(String name) {
    
        return repo.findByName(name)
                .zipWhen((List<Student> students) -> {
                    return repo.findAnotherName(anothName, 1).collectList()
                            .flatMap(anotherStudents -> someAsyncMethod(anotherStudents));
                }, ((students, o) -> students));
    }