简体   繁体   English

Java mono 用 arguments 调用 void 方法

[英]Java mono call void method with arguments

I have the following method:我有以下方法:

void save(User user);

And I call this method in this function:我在这个 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 ?有没有一种方法可以调用save方法而无需使用flatMap

I tried the then but it does not accept lambdas?我尝试了then但它不接受 lambdas?

Any other option?还有其他选择吗?

Thanks谢谢

peek seems useful here, perhaps? peek在这里似乎很有用,也许?

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

reactor.core.publisher.Mono provides various methods which runs based upon need or signal. reactor.core.publisher.Mono提供了根据需要或信号运行的各种方法。 Not sure why not wanted to use flatMap .不知道为什么不想使用flatMap You can use various other methods of Mono to call repository.save(...) .您可以使用Mono的各种其他方法来调用repository.save(...) Eg例如

  • map() - takes lamda/Function object which provides T input and R return map() - 接受 lamda/Function object 提供 T 输入和 R 返回
  • doOnNext - takes lamda/Consumer object which takes T doOnNext - 需要 lamda/Consumer object 需要 T
  • doOnEach - takes lamda/Consumer object which takes T doOnEach - 需要 lamda/Consumer object 需要 T
  • doOnSubscribe - takes lamda/Consumer object which takes T doOnSubscribe - 需要 lamda/Consumer object 需要 T

These all methods evaluate when Mono will be subscribed.这些所有方法都会评估何时订阅 Mono。

Also not sure which repository you are using because most of the Repository (from Spring Data Reactive) returned object after persistence eg:也不确定您正在使用哪个存储库,因为大多数Repository (来自 Spring 数据反应式)在持久性后返回 object 例如:

<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:如果需要从数据库中加载 object 更新并返回它,那么可以考虑以下代码作为示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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