'Converting a mono object into two different mono object and the root mono is executing two times

Suppose I have create a Student entity and storing it into database using reactive.

  Student student{
    id;
    name;
    institutionId; 
    courseId;
}

I am storing this student entity using a reactive repository and in response finding a Mono. Now we are getting two mono String instituteName and courseName using instituteId and courseId reactively.

Mono<Student> monoStudent = studentRepository.save(student);

Mono<String> institutionName = monoStudent.flatMap(student -> 
                            institutionRepository.findById(student.getInstitutionId))
              .map(institution -> institution.getName());

Mono<String> courseName = monoStudent.flatMap(student -> 
                   courseRepository.findById(student.getCourseId))
              .map(course -> course.getName());

We are using monoStudent into two different chain to get institutionName and courseName, as a result studentRepository.save(student) is executing two times. How I could creating two different object without executing studentRepository.save(student) two times?



Solution 1:[1]

Consider using cache on monoStudent

Mono<Student> cachedMonoStudent = studentRepository.save(student).cache();

https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#cache--

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kokodyn