【问题标题】:How use thenEmpty and then thenReturn in Spring WebFlux?在 Spring WebFlux 中如何使用 thenEmpty 然后 thenReturn?
【发布时间】:2020-03-30 07:39:57
【问题描述】:

我是 Spring WebFlux 的新手,但遇到了问题。我想返回类似Mono<String> 的内容,如下所示:

@PostMapping("/test")
public Mono<String> test(){
    return Mono.just("Test String")
           .thenEmpty(it -> {
                // Do something I need
                System.out.println("Print somethings");
           })
           .thenReturn("Return String");
}

我希望该方法返回Return String,但它什么也没返回。有什么问题?

【问题讨论】:

  • 好像是java但是现在不能编译
  • @firegloves 对不起,我使用kotlin 并试图转换为java,但它可能有错误
  • 如果您在 kotlin 中需要帮助,为什么不在 kotlin 中发帖?
  • @firegloves 因为知道 kotlin 的人很少。我修复了这个错误。
  • 为什么要清空单声道?有什么原因吗?你读过 thenEmpty 的行为吗?你到底需要什么?

标签: spring-boot reactive-programming spring-webflux


【解决方案1】:

thenEmpty 将被调用并返回 Mono 作为管道顺序的一部分。由于 Mono 返回,管道中的其余运算符无法正常工作。如果你想使用 thenReturn 然后使用下面的代码。

@PostMapping("/test")
public Mono<String> test(){
    return Mono.just("Test String")
           .doOnNext(s -> {
                    // do what you want
                })
           .thenReturn("Return String");
}

【讨论】:

    【解决方案2】:

    你可以试试这样的:

       @PostMapping("/test") public Mono<String> test(){
            return Mono.just("Test String")
                    .doOnNext(s -> {
                        // do what you want
                    })
                    .map(s -> {
                        return "done";
                    });
       }
    

    您可以根据需要使用其他doOn* 方法。例如doOnSuccessdoOnError

    如果您需要操作数据(但保留返回类型),则可以使用map

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2018-01-26
      • 2019-07-11
      • 2019-01-15
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多