Java mono call void method with arguments

Viewed 55

I have the following method:

void save(User user);

And I call this method in this function:

userRepository.findById(id)
              .flatMap(user -> {
                   userRepository.save(user);

                   return Mono.just(userMapper.map(user));
              });

Is there a way that I can call the save method without the need to use a flatMap?

I tried the then but it does not accept lambdas?

Any other option?

Thanks

1 Answers

reactor.core.publisher.Mono provides various methods which runs based upon need or signal. Not sure why not wanted to use flatMap. You can use various other methods of Mono to call repository.save(...). E.g.

  • map() - takes lamda/Function object which provides T input and R return
  • doOnNext - takes lamda/Consumer object which takes T
  • doOnEach - takes lamda/Consumer object which takes T
  • doOnSubscribe - takes lamda/Consumer object which takes T

These all methods evaluate when Mono will be subscribed.

Also not sure which repository you are using because most of the Repository (from Spring Data Reactive) returned object after persistence e.g.:

<S extends T> Mono<S> save(S entity)

If there is need to load an object from database update it and return it then below code can be consider as example:

fun update(id: Long, person: Person): Mono<Person> {
        return personRepository
            .findById(id)
            .map {it ->
                    p?.let {
                        it.name = p.name
                        it.password = p.password
                    }
                return@map it
                }.flatMap(personRepository::save)
    }
Related