0

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.

Ravi sinha
  • 119
  • 4
  • 12

2 Answers2

0

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. -

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • but for inserting into db i need to subscribe or block. with doOnSuccess data will not be inserted in Db. How to achieve that with this approach? – Ravi sinha Sep 07 '20 at 23:27
  • See added paragraph at the end of my answer - By adding a `Consumer`, you ARE subscribing to an event...the event of the user having successfully been added to the repository. – CryptoFool Sep 07 '20 at 23:33
  • Thanks for the suggestion. But sometimes this doOnSuccess gives me Null object.Not all the time. Also if i am putting a delay of 2 ms its working fine. Any suggestion? – Ravi sinha Sep 07 '20 at 23:47
  • That's strange. I have no idea what that's about. That behavior will be a function of your 'userRepository' implementation, which I obviously can't know anything about. Maybe you need to ignore any Null objects that you get, and you'll eventually get the one you really want to act on. I can't recall if `doOnSuccess` should cause your Consumer to be only called once, or if it might be called multiple times. I would think the former, but then I don't know what you'd do if you got Null. – CryptoFool Sep 08 '20 at 00:36
0

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.