I want to convert mono to object java without using block()/blockFirst()/blockLast(). Please tell me the way to convert it.
3 Answers
The official path is block(), which should serve as a warning that you may be doing something wrong, because blocking a non-blocking system is like shooting yourself in the foot.
In fact so much so that we recently forbid to do so on some of the non-blocking Schedulers of Reactor by throwing an exception when using these APIs:
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-1
If you really like to shoot yourself in the foot, there is always the antipattern solution of .toFuture().get()... ¯\_(ツ)_/¯
1 Comment
I was facing similar error while generating sequence/id on MongoDb document/model using ReactiveMongoDbRepository and WebFlux in the Spring boot 2. I have handle it using the .toFuture().get() as promise on non-blocking method/function.
@Override
public long generateSequence(final String sequenceName) throws InterruptedException, ExecutionException {
return mongoOperations.findAndModify(new Query(Criteria.where("_id").is(sequenceName)),
new Update().inc("sequence", 1), DatabaseSequence.class).doOnSuccess(object -> {
logger.debug("databaseSequence is evaluated: {}", object);
}).toFuture().get().getSequence();
}
1 Comment
Declare the field you want to save the value of Mono outside the method. Use subscribe() to get the value and assign to the variable you declared. Check this code below and comment for queries. This worked for me. Hope this helps. Please suggest if corrections are to be made for this approach
private ExpenseEntity expenseEntity1;
private UserEntity payerEntity1;
private Double amountSpent;
// SPLIT CALCULATION
public Mono<Map<Long, Double>> findSplit(SplitDTO splitDTO) {
Mono<ExpenseEntity> expenseEntity =
expensePersistence.findExpenseById(splitDTO.getExpenseId());
expenseEntity.subscribe(expense -> {
expenseEntity1= expense;
amountSpent = expense.getAmount();
});
Mono<UserEntity> payerEntity =
userPersistence.findUserById(splitDTO.getPayerId());
payerEntity.subscribe(payer -> {
payerEntity1 = payer;
}
);
block,blockFirstorblockLast