简体   繁体   中英

Java mono call void method with arguments

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

peek seems useful here, perhaps?

userRepository.findById(id)
  .peek(this::save)
  .map(userMapper);

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(...) . Eg

  • 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 eg:

<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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM