1
votes

I am new to reactor programming,and need some help on MONO/Flux

I have POJO class

Employee.java

class Employee {
   String name
}

I have Mono being returned on hitting a service, I need to extract the name from Mono as a string.

Mono<Employee> m = m.map(value -> value.getName()) 

but this returns again a Mono but not a string. I need to extract String value from this Mono.

2
to retrieve object from mono you have to block ref:projectreactor.io/docs/core/release/api/reactor/core/publisher/… - Manoj Krishna

2 Answers

2
votes

You should do something like this:

m.block().getName();

This solution doesn't take care of null check.

A standard approach would be:

Employee e = m.block();
if (null != e) {
   e.getName();
}

But using flux you should proceed using something like this:

Mono.just(new Employee().setName("Kill"))
    .switchIfEmpty(Mono.defer(() -> Mono.just(new Employee("Bill"))))
    .block()
    .getName();

Keep in mind that requesting for blocking operation should be avoided if possible: it blocks the flow

0
votes

You should be avoiding block() because it will block indefinitely until a next signal is received.

You should not think of the reactive container as something that is going to provide your program with an answer. Instead, you need to give it whatever you want to do with that answer. For example:

employeeMono.subscribe(value -> whatYouWantToDoWithName(value.getName()));