sasska94
sasska94

Reputation: 13

Collecting int value from the Mono<Entity> object using WebFlux

What is the correct way for collecting the value from the Mono object? I have an entity called Student which has both user and student id values.

Mono<Student> student = studentRepository.findStudentByUserid(id);

and I want to use studentId (student.getStudentId()) to save a new value in different table

StudentSubject ss;
ss.setStudentId(student.getStudentId());
studentsubjectRepository.save(ss);

What is the best approach?

Upvotes: 1

Views: 695

Answers (1)

Brian Clozel
Brian Clozel

Reputation: 59211

Your question lacks a bit of details, so I'll assume some things from this point.

Let's say your app is using this code:

Mono<StudentSubject> studentSubject = studentRepository.findStudentByUserid(id)
    .flatMap(student -> {
        StudentSubject subject = new StudentSubject();
        subject.setStudentId(student.getStudentId());
        return studentsubjectRepository.save(subject);
    });

Using the flatMap operator allows you to chain calls in reactive fashion.

Several things can happen here:

  • there is a student with that id, a subject is created with that information and is returned, as long as something subscribes to this Mono. The subscription part usually happens in Spring WebFlux so you just need to return that Mono from your controller method.
  • there is no student with that id, so the first repository will return Mono.empty(). In this case, your flatMap operator won't be called and an empty publisher is effectively returned; no StudentSubject is created. Depending on the expected behavior of your app, you could look into defaultIfEmpty or switchIfEmpty operators to deal with that case
  • there is an error. You can let the error flow throw the pipeline and being handled by WebFlux, or you can deal with it directly with onError* operators.

If you're new to Reactor, you can always add a log() operator wherever you want in the chain (as a regular operator) and you'll see in the logs what happens precisely.

Upvotes: 2

Related Questions