How to get User object from Mono<User> without blocking it in Java?

912 Views Asked by At

I have a repository call which will give me Mono .

ex:

    private User getUserData (User user)
{
 Mono<User> monoUser=userRepository.insert(user);
  User user= monoUser.block; 
return user;
}

How to achieve this without blocking in spring reactive. I don't want to do monoUser.block to get User object.

After getting userObject i need to convert id to UserId via Mapstruct.Also i want to achieve this without blocking so that i will be using reactive feature.

2

There are 2 best solutions below

4
On

There are a number of things you can do with a Mono instead of calling block, things that will not block. One thing you can do is attach a Consumer to it that gets called when the Mono's action completes successfully. The signature of the method to do that (on the Mono) is:

Mono<T> doOnSuccess(Consumer<? super T> onSuccess)

So then you can go on working, and your consumer will get called when the action completes. That call would then initiate whatever actions you want to have performed after the user is added.

You put code in your Consumer that writes to the database. If that object needs information, like a handle to the database to write to, you can hand it that information when you construct the object, before passing it in to the doOnSuccess call. -

0
On

The correct way to handle this would be to link your Mono<> output with the function signature and consume it by calling the getUserData method in your Mono pipeline. To consume it you'll have to maintain a complete reactive pipeline where all your operations are linked to one another through the various operations like map / flatmap. Alternatively if you just want to print the user inserted in your logs you can make use of .doOnNext() to print the same, this would run in a different thread which would not block your main Mono thread.